1、传值的校验
- 引入 prop-types
import PropTypes from 'prop-types'
- 对
propTypes
进行设置 (注意是 小写p 开头,和包名的 大写P 开头不一样)
// 单类型校验
[组件名].propTypes = {
[键名]: PropTypes.[类型]
}
// 组合类型校验
[组件名].propTypes = {
[键名]: PropTypes.oneOfType( [PropTypes.[类型], ...] )
}
// 必须要传过来的
[组件名].propTypes = {
[键名]: PropTypes.[类型].isRequired
}
Parent.js
import React, {Component, Fragment} from 'react'
import Child from './Child'
class Parent extends Component {
constructor(props){
super(props)
this.state = {
data: 'parent => child'
}
}
render(){
return(
<Fragment>
<Child data={this.state.data}></Child>
</Fragment>
)
}
}
export default Parent
Child.js
import React, {Component, Fragment} from 'react'
import PropTypes from 'prop-types'
class Child extends Component {
constructor(props){
super(props)
}
render(){
return(
<Fragment>
<div>{this.props.data}</div>
</Fragment>
)
}
}
Child.propTypes = {
data: PropTypes.string
}
export default Child
- 校验结果不正确会在控制台报警告,程序依旧能执行
2、传值的默认值设置
- 对
defaultProps
进行设置
[组件名].defaultProps= {
[键名]: [默认值]
}
- Child.js
import React, {Component, Fragment} from 'react'
class Child extends Component {
constructor(props){
super(props)
}
render(){
return(
<Fragment>
<div>{this.props.hello}</div>
</Fragment>
)
}
}
Child.defaultProps = {
hello: 'hello'
}
export default Child