屬性驗(yàn)證是強(qiáng)制正確使用組件的有效方法。這將有助于在開發(fā)過程中避免將來的錯誤和問題,一旦應(yīng)用程序變得更大。它還使代碼更具可讀性,因?yàn)槲覀兛梢钥吹矫總€組件應(yīng)該如何使用。
在這個實(shí)例中,我們用我們需要的所有道具來創(chuàng)建App組件。App.propTypes用于道具驗(yàn)證。如果一些道具沒有使用我們分配的正確類型,我們將收到控制臺警告。在我們指定驗(yàn)證模式之后,我們將設(shè)置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'));