在类型传递中,我们要对prop中的类型进行限制
最新版本有一个PropTypes进行处理
安装:npm i prop-types
引入:import PropTypes from 'prop-types'
使用:
Person.propTypes = { //你类的属性规则 ,, static相当于直接给类本身添加了属性
name: PropTypes.string.isRequired,
sex: PropTypes.string,
age: PropTypes.number,
spack: PropTypes.func
}
指定默认标签:
Person.defaultProps = {
sex:'男',//sex默认值为男
age:18 //age默认值为18
}
如果是在类里面;
class Person extends React.Component{
constructor(props){
//构造器是否接收props,是否传递给super,取决于:是否希望在构造器中通过this访问props
// console.log(props);
super(props)
console.log('constructor',this.props);
}
//对标签属性进行类型、必要性的限制
static propTypes = {
name:PropTypes.string.isRequired, //限制name必传,且为字符串
sex:PropTypes.string,//限制sex为字符串
age:PropTypes.number,//