属性验证是强制正确使用组件的有效方法。这将有助于在开发过程中避免将来的错误和问题,一旦应用程序变得更大。它还使代码更具可读性,因为我们可以看到每个组件应该如何使用。
在这个实例中,我们用我们需要的所有道具来创建App组件。App.propTypes用于道具验证。如果一些道具没有使用我们分配的正确类型,我们将收到控制台警告。在我们指定验证模式之后,我们将设置App.defaultProps。
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;
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));