子组件通过this.props
属性接受传值的同时也可以对其进行类型检查
示例组件<Message handleClick={this.alertMessageById} index={index} content={content}/>
import React from 'react'
import PropTypes from 'prop-types'
class Message extends React.Component {
constructor(props) {
super(props)
this.handleClick = this.handleClick.bind(this)
}
render() {
return (
<div onClick={this.handleClick}>{this.props.content}</div>
)
}
handleClick() {
this.props.alertMessageById(this.props.index);
}
}
// 此处对传来的值做类型检查
Message.propTypes = {
index: PropTypes.number,
content: PropTypes.string.isRequired,
alertMessageById: PropTypes.func
}
export default Message;
需要注意的是PropTypes
只作运行时检查,会有warn
level的log打印在控制台