English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Property validation is an effective method for enforcing correct usage of components. This will help avoid future errors and issues during the development process, once the application becomes larger. It also makes the code more readable, as we can see how each component should be used.
In this instance, we use all the props we need to create the App component. App.propTypes is used for prop validation. If some props are not used with the correct type we assigned, we will receive a console warning. After we specify the validation mode, we will set App.defaultProps.
import React from 'react'; class App extends React.Component { render() { return ( <div> <h3Array: {this.props.propArray}/h3> <h3Bool: {this.props.propBool ? "True..." : "False..."}/h3> <h3Func: {this.props.propFunc(3/h3> <h3Number: {this.props.propNumber}/h3> <h3String: {this.props.propString}/h3> <h3Object: {this.props.propObject.objectName}1}<//h3> <h3Object: {this.props.propObject.objectName}2}<//h3> <h3Object: {this.props.propObject.objectName}3}<//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'));