propType检测数据类型
import PropTypes from 'prop-types';
class Counter extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<button style={buttonStyle} onClick={this.onClickIncrementButton}>+</button>
<button style={buttonStyle} onClick={this.onClickDecrementButton}>-</button>
<span>{caption} count: {this.state.count}</span>
</div>
);
}
}
//检查传入的prop是否为想要的数据类型,isrequired表示该数据类型是必须的,不能为空
Counter.propTypes = {
caption: PropTypes.string.isRequired,
initValue: PropTypes.number
};
defaultProps设置默认prop
import PropTypes from 'prop-types';
class Counter extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<button style={buttonStyle} onClick={this.onClickIncrementButton}>+</button>
<button style={buttonStyle} onClick={this.onClickDecrementButton}>-</button>
<span>{caption} count: {this.state.count}</span>
</div>
);
}
}
//设置传入的prop默认值
Counter.defaultProps= {
initValue: 0
};
网友评论