Type detection using PropTypes
React.PropTypes.string.isRequireCheck whether name is a string and is required.When invalid values are provided for prop, a warning is displayed in the JavaScript console.MyComponent.propTypes = {/ / you can define one.jsThe original type of prop, by default, is optional.OptionalArray: React.PropTypes.array,
optionalBool: React.PropTypes.bool,
optionalFunc: React.PropTypes.func,
optionalNumber: React.PropTypes.number,
optionalObject: React.PropTypes.object,
optionalString: React.PropTypes.string,
optionalSymbol: React.PropTypes.symbol,
// Anything that can be rendered: numbers, strings, elements or arrays (or fragments).OptionalNode: React.PropTypes.node,
// ReactelementOptionalElement: React.PropTypes.element,
// You can also declare that prop is an instance of a class. The instanceof operator of JS is used internally.OptionalMessage: React.PropTypes.instanceOf(Message),
// You can ensure that your prop is restricted to a specific value by enumerating it as an enumeration.OptionalEnum: React.PropTypes.oneOf(['News', 'Photos']),
// It can be one of many types of objects.OptionalUnion: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number,
React.PropTypes.instanceOf(Message)
]),
// Some type of arrayOptionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),
// An object with some type of attribute value.OptionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number),
// Objects of specific styleOptionalObjectWithShape: React.PropTypes.shape({
color: React.PropTypes.string,
fontSize: React.PropTypes.number
}),
// You can use `isRequired'to connect to any of the above types to ensure that a warning is displayed if props are not provided.RequiredFunc: React.PropTypes.func.isRequired,
// Any data typeRequiredAny: React.PropTypes.any.isRequired,
// You can also specify a custom type checker. If the check fails, it should return a Error object. No `console..warn`Or throw, because this will not work in `oneOfType`.CustomProp: function (props, propName, componentName) {If (! /matc)Hme/.test(props[propName])) {
return new Error(
'Invalid prop `' + propName + '` supplied to' +
' `' + componentName + '`. Validation failed.'
);
}
},
// You can also provide custom type checkers for `arrayOf` and `objectOf`. If the check fails, it should return a Error object./ / the inspector will call the validation function for every key in the array or object./ / the checker has twoThe first parameter is the array or the object itself, and the second is the key of the current item.CustomArrayProp: React.PropTypes.arrayOf (function (propValue, key, COM)PonentName, location, propFullName) {If (/matchme/.test (propValue[key])) {Return new ErRor ('Invalid prop '' + propFullName + '' supplied to'+'' + componentName + '.Validation failed.');}})};Use the defaultProps attribute to define the default value of props.