React v15.5.之后的版本需要单独安装prop-types
才能使用类型检查
1. 引入
import PropTypes from 'prop-types'
2. 定义规则
ComponentFooter.propTypes = {
userid: PropTypes.number.isRequired
}
number为类型,isRequired为此参数必须传入
3. 设置默认值
ComponentFooter.defaultProps = {
username: '默认的值'
}
4. 传递所有参数
{...this.props}
完整代码
var React = require('react')
var ReactDom = require('react-dom')
import PropTypes from 'prop-types'
import ComponentFooter from './components/footer'
render() {
var component = <ComponentHeader />
return (
<div>
<ComponentFooter userid={111} />
</div>
)
}
}
ComponentFooter.propTypes = {
userid: PropTypes.number.isRequired
}
ComponentFooter.defaultProps = {
username: '默认的值'
}
ReactDom.render(<Index />, document.getElementById('app'))