react-- propTypes类型检查
- 学习资源推荐:https://blog.csdn.net/qq_42813491/article/details/90213353
-
承接上文 https://blog.csdn.net/qq_42813491/article/details/92097864
-
引入prop-types进行类型检查
-
详情参见本段代码末尾
import React, { Component } from 'react'
import PropTypes from 'prop-types';
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
Count: this.props.initCount || 0
}
}
add = () => {
this.setState({
Count: this.state.Count + 1
})
}
render() {
const { order } = this.props;
return (
<div>
<p>
<span>第{order}个按钮:</span>
<button onClick={this.add}>click me</button>
<span>当前数值为{this.state.Count}</span>
</p>
</div>
)
}
}
Counter.propTypes = {
order: PropTypes.string.isRequired,
initCount: PropTypes.number
}
export default Counter;
-
写个错误的类型
-
效果