说说React的事(五)Props验证

说说React的事

Winter

2017-10-12

前面说到props是组件之间交流的一种方式,是数据流通的桥梁。React提供一项机制就是我们可以设置Props属性的类型,这样Props的属性假如一旦被设置为number型的时候,就不能传字符串值给它了,这个便是Props的验证。

通过Props的验证,我们可以让组件结构变得清晰,防止盲目传递参数,而造成产生不可预知的bug的隐患。

Props的验证请看如下片段

App.jsx

import React from 'react';

class App extends React.Component {
   render() {
      return (
         <div>
            <h3>Array: {this.props.propArray}</h3>
            <h3>Bool: {this.props.propBool ? "True..." : "False..."}</h3>
            <h3>Func: {this.props.propFunc(3)}</h3>
            <h3>Number: {this.props.propNumber}</h3>
            <h3>String: {this.props.propString}</h3>
            <h3>Object: {this.props.propObject.objectName1}</h3>
            <h3>Object: {this.props.propObject.objectName2}</h3>
            <h3>Object: {this.props.propObject.objectName3}</h3>
         </div>
      );
   }
}

App.propTypes = {
   propArray: React.PropTypes.array.isRequired,
   propBool: React.PropTypes.bool.isRequired,
   propFunc: React.PropTypes.func,
   propNumber: React.PropTypes.number,
   propString: React.PropTypes.string,
   propObject: React.PropTypes.object
}

App.defaultProps = {
   propArray: [1,2,3,4,5],
   propBool: true,
   propFunc: function(e){return e},
   propNumber: 1,
   propString: "String value...",
	
   propObject: {
      objectName1:"objectValue1",
      objectName2: "objectValue2",
      objectName3: "objectValue3"
   }
}

export default App;

如上,假如我们给propBool赋值为string “123”时,编译是不会通过的,而且当我们又设置了属性是isRequired,那意味着这个值一定要从外部传进该组件,否则也会出现编译错误。

 

 

第25篇《说说React的事(五)Props验证》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

0条评论