1、在需要验证的组件引入依赖包
import PropTypes from 'prop-types'
2、使用位置:
class testUnit extends PureComponent {
constructor(props) {
super(props);
this.state = { }
}
render(){
console.log("子组件渲染")
let {msg} = this.props
return(
<div style={{padding:10}}>{msg}</div>
)
}
}
testUnit.propTypes={ // 在这里使用 类名.propTypes{ // 接收的值 }
msg: PropTypes.string
}
3、PropTypes提供了大量的验证器 如:
optionalArray: PropTypes.array, // 数组
optionalBool: PropTypes.bool, // 布尔
optionalFunc: PropTypes.func, // 函数
optionalNumber: PropTypes.number, // 数值
optionalObject: PropTypes.object, // 对象
optionalString: PropTypes.string, // 字符
optionalSymbol: PropTypes.symbol, // es6新增的symbol类型
...
4:、控制台输出效果:
参考官方文档:https://zh-hans.reactjs.org/docs/typechecking-with-proptypes.html#gatsby-focus-wrapper