每个组件都有自己的props 参数。这个参数,是从父组件接收到的一些属性。
本篇主要介绍,接收参数时,如何对参数的类型做校验;如何定义参数的默认值。
接收参数的类型的校验:
PropTypes
我们首先要引入 PropTypes,脚手架中自带了 prop-types包。然后使用如下。
import React, {
Component
} from 'react';
import PropTypes from 'prop-types';
class TodoItem extends Component {
constructor(props) {
super(props);
this.handleDelete = this.handleDelete.bind(this)
}
handleDelete() {
const {
deleteItem,
index
} = this.props;
deleteItem(index);
}
render() {
const {
content
} = this.props;
return (
<div onClick={this.handleDelete}>{content}</div>
)
}
}
TodoItem.propTypes = {
content: PropTypes.string.isRequired,
deleteItem: PropTypes.func,
index: PropTypes.number
}
export default TodoItem
定义参数的默认值
DefaultProps
import React, {
Component
} from 'react';
import PropTypes from 'prop-types';
class TodoItem extends Component {
constructor(props) {
super(props);
this.handleDelete = this.handleDelete.bind(this)
}
handleDelete() {
const {
deleteItem,
index
} = this.props;
deleteItem(index);
}
render() {
const {
content,
test
} = this.props;
return (
<div onClick={this.handleDelete}>{test} - {content}</div>
)
}
}
TodoItem.propTypes = {
test: PropTypes.string.isRequired,
content: PropTypes.string.isRequired,
deleteItem: PropTypes.func,
index: PropTypes.number
}
TodoItem.defaultProps = {
test: "hello world"
}
export default TodoItem
官网介绍在这儿:【更详细】