React Tutorial - Props Validation
Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.
How to validate Props? It's actually very simple. React provides us with PropTypes for validation. When the data we pass to Props is invalid (that is, the data type passed to Props does not match the validated data type), a warning message will be issued in the console.
See the following example
var Propsva = React.createClass({
propTypes: {
optionalArray: React.PropTypes.array,
optionalBool: React.PropTypes.bool,
optionalFunc: React.PropTypes.func,
optionalNumber: React.PropTypes.number,
optionalObject: React.PropTypes.object,
optionalString: React.PropTypes.string,
},
getDefaultProps:function(){
return {
optionalArray: ['onmpw.com','——track memory blog'],
optionalBool: true,
optionalFunc: function (arg) {
console.log(arg);
},
optionalNumber: 3,
optionalObject: {
object1: "objectvalue1",
object2: "objectvalue2",
object3: "objectvalue3",
},
optionalString: "My Onmpw",
};
},
render:function(){
return (
<div>
<h3>Array:{this.props.optionalArray}</h3>
<h3>Bool:{this.props.optionalBool}</h3>
<h3 onClick={this.props.optionalFunc}>Func:click</h3>
<h3>Number:{this.props.optionalNumber}</h3>
<h3>Object:{this.props.optionalObject.object1}</h3>
<h3>Object:{this.props.optionalObject.object2}</h3>
<h3>Object:{this.props.optionalObject.object3}</h3>
<h3>String:{this.props.optionalString}</h3>
</div>
);
}
});
ReactDOM.render(
<Propsva />,
document.getElementById('content')
);
Of course, there is nothing wrong with the above example. Let's modify the above example
getDefaultProps:function(){
return {
optionalArray: 'onmpw.com——Memory Blog',
optionalBool: true,
optionalFunc: function (arg) {
console.log(arg);
},
optionalNumber: 3,
optionalObject: {
object1: "objectvalue1",
object2: "objectvalue2",
object3: "objectvalue3",
},
optionalString: "My Onmpw",
};
},
Then, we will find the following warning in the console
Warning: Failed propType: Invalid prop `optionalArray` of type `string` supplied to `Propsva`, expected `array`.
This is one case, verifying the data type of Props. Another case is to verify whether Props has a value. See the following code
propTypes: {
optionalArray: React.PropTypes.array.isRequired,
optionalBool: React.PropTypes.bool.isRequired,
optionalFunc: React.PropTypes.func,
optionalNumber: React.PropTypes.number,
optionalObject: React.PropTypes.object,
optionalString: React.PropTypes.string,
},
Add isRequired after React.PropTypes.array and React.PropTypes.bool to indicate that optionalArray and optionalBool must have values.
getDefaultProps:function(){
return {
optionalFunc: function (arg) {
console.log(arg);
},
optionalNumber: 3,
optionalObject: {
object1: "objectvalue1",
object2: "objectvalue2",
object3: "objectvalue3",
},
optionalString: "My Onmpw",
};
},
In the above code, we remove optionalArray and optionalBool, and then run the code in the browser, and you will find the following error in the console:
Warning: Failed propType: Required prop `optionalArray` was not specified in `Propsva`.
Warning: Failed propType: Required prop `optionalBool` was not specified in `Propsva`.
Of course, the above are just two simple cases. There are many other things and forms of verification for Props. For details, we can refer to the official React documentation .
Here we have a knowledge point that needs to be explained, which is getDefaultProps. This is the default assignment of Props. See the following code
var ComponentDefaultProps = React.createClass({
getDefaultProps: function() {
return {
value: 'Default Value'
};
},
render:function(){
return (
<div>{this.props.value}</div>
)
}
});
ReactDOM.render(
<ComponentDefaultProps />,
document.getElementById('content')
);
getDefaultProps() can ensure that when the parent component does not pass in Props, the current component can be guaranteed to have the default Props value. It should be noted that the return result of getDefaultProps will be cached. Therefore, we can use Props directly without having to manually write some meaningless repetitive code.
This is the end of the introduction to Props verification. I hope this article will be helpful to you.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
React Tutorial - Transferring Props
Publish Date:2025/03/16 Views:185 Category:React
-
React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.
React Tutorial: Props Anti-Pattern
Publish Date:2025/03/16 Views:183 Category:React
-
React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.
Rendered fewer hooks than expected error in React
Publish Date:2025/03/16 Views:50 Category:React
-
When we use a hook after a condition that may return a value, we get the error "Rendered fewer hooks than expected. This may be caused by an accidental early return statement". To fix this error, you need to move all React hooks to any condition that
Fix Uncaught ReferenceError: useState is not defined in React
Publish Date:2025/03/15 Views:142 Category:React
-
When we use the useState hook in our code but forget to import it, it generates the error Uncaught ReferenceError: useState is not defined. To fix this error, you need to import the hook before using it import {useState} from react . // ?️
React error Uncaught ReferenceError: process is not defined solution
Publish Date:2025/03/15 Views:117 Category:React
-
To resolve the “Uncaught ReferenceError: process is not defined” error in React, open a terminal in the root directory of your project and update the version of the `react-scripts` package by running `npm install react-scripts@latest` and reinstal
How to solve the "Function components cannot have string refs" error in React
Publish Date:2025/03/15 Views:139 Category:React
-
When we use a string as a reference in a function component, we get the error "Function components cannot have string refs". To fix this error, we need to use the useRef() hook to get a mutable ref object that we can use as a component.
React Error Property 'X' does not exist on type 'Readonly<{}>'
Publish Date:2025/03/15 Views:140 Category:React
-
The React.js error “Property does not exist on type 'Readonly'” occurs when we try to access the props or state of an untyped class component. To fix the error, you need to use generics on the React.Component class to type the props or state of th
Solve React's Unexpected default export of anonymous function error
Publish Date:2025/03/15 Views:120 Category:React
-
When we try to export an anonymous function using default export, it results in the warning “Unexpected default export of anonymous function.” To fix this error, you need to give the function a name before exporting it.
React error Type '() => JSX.Element[]' is not assignable to type FunctionCompo
Publish Date:2025/03/15 Views:52 Category:React
-
When we try to return an array of elements from a function component, a React.js error “Type '() => JSX.Element[]' is not assignable to type FunctionComponent” occurs. To fix the error, you need to wrap the array of elements in a React fragment.