PropTypes与DefaultProps

文档连接:https://reactjs.org/docs/typechecking-with-proptypes.html

 PropTypes:就是用来验证组件实例的属性是否符合要求,PropTypes 告诉 React,这个 title 属性是必须的,而且它的值必须是字符串。

defaultProps :方法可以用来设置组件属性的默认值。

 1 import React,{Component} from 'react';
 2 import PropsTypes from 'prop-types'; //引入
 3 
 4 class todoitem extends Component{
 5     constructor(props){
 6         super(props);
 7         this.handleClick = this.handleClick.bind(this) 
 8     }
 9 
10     render(){
11         const { item, content } = this.props
12         return (
13         <li onClick={this.handleClick}>{ content }---{ item }</li>
14         )
15     }
16 
17     handleClick(){
18         const { delitem ,index } = this.props
19         delitem( index); 
20     }
21 }
22 // propTypes当内容为空就不检测 ,添加isRequired就变为必填
23 todoitem.propTypes = {
24     content:PropsTypes.string.isRequired,
        //oneOfType传入的值为括号中的其中一个
25     item:PropsTypes.oneOfType([PropsTypes.number, PropsTypes.string]),
26     delitem: PropsTypes.func,
27     index: PropsTypes.number
28 }
29 //defaultProps配置默认值,当没有传入值就显示为设置的默认值
30 todoitem.defaultProps ={
31     content:'没有传入值'
32 }
33 export default  todoitem;

 

posted @ 2020-06-27 23:11  雪糕战士  阅读(175)  评论(0编辑  收藏  举报