The prop-types third-party library is used to detect the types of variables in the props of the component, and the prop-typesprops

Source: Internet
Author: User

The prop-types third-party library is used to detect the types of variables in the props of the component, and the prop-typesprops

1. Introduction-JavaScript is a bear child

1.1 For JSer, js is free, but there are also a lot of troubles. Javascript is often such a bear child. Many times it is not as well-behaved as C and java. So it brings us a lot of troubles

<1> when running, the console reports an error: uncaught error. This is particularly annoying because the system tells us that there is an error but does not tell us where the error occurred. Just think about it. When you travel to a certain place, a local bear child keeps following you with a smile and tells you, "You're wrong !". But if you don't tell you how to go, will you really want to beat him? (╬  ̄)

<2> A fixed error was reported during running. However, we found that this TM was completely an incorrect report. I even went to stackoverflow to find the answer, but I found that the error scenario of the question is different from my own. Let's go back to the scenario 1. If the bear child tells you the route with great care, you will find that the bear child has been playing hard in the dark, and you will have to sleep on the street at night, do you want to beat him more than in scenario 1? (╬  ̄)

<3> you write a variable type subjectively. For example, you can write string 1 as number 1, but the system does not report an error message "kindly. (We do not need to make a special type declaration. Of course, no error prompt will be reported.) This may be the source of your next bug. Let's go back to the scenario 1 and 2. If this bear child knows that you are a foreigner, it is a wrong path, but when you ask, "Are you on the right path ?" He nodded with a smile like a spring breeze, so that you can go to the dark with confidence and hope. I think you will not feel better at this time than those in 1 and 2 (╬  ̄)

<2> moderate situations are sometimes difficult to avoid

<1> we can determine the situation by familiarizing ourselves with the six major uncaught errors. (I will discuss this issue in the next article)

<3> the situation in this article can be completely avoided by the type detection method. This is what I mentioned in this article.

This section mainly discusses the use of prop-types, a type detection library supporting react.

The content I introduced in this article today is to use react's propTypes for type detection ,. As the name suggests, prop-types checks the type of variables in the props object in the react component, because props is the pipe of the react data stream, with prop-types, we can easily monitor the variable types of most data in react. First, we will introduce the basic usage of propTypes.

2. Getting started with prop-types

2.1 first, you need to install a third-party package named prop-types through npm install prop-types on the terminal.

2.2 then, use the following method to check the type of variables in your props component:

YourComponent. propTypes = {attribute 1: variable type of attribute 1, attribute 2: variable type of attribute 2 //...}

3. Full solution for propTypes

3.1 Use propTypes to detect all data type variables

import React from 'react' class Son extends React.Component{ render(){ return (<div style ={{padding:30}}>    {this.props.number}    <br/>    {this.props.array}    <br/>    {this.props.boolean.toString()}   </div>)   }}class Father extends React.Component{ render(){  return (<Son    number = {'1'}    array = {'[1,2,3]'}    boolean = {'true'}    />)   }}

In this example, we pass attributes from the parent component to the child component through props. You originally tried to pass a number to Son through the three attributes number, array, and boolean, array and a Boolean value, but because you are exhausted, they are all written as strings, although rendering is normal, however, this may cause errors when you call some methods next, and the system does not provide any prompts.

Let's add propTypes type detection to it:

import React from 'react'import PropTypes from 'prop-types';class Son extends React.Component{ render(){  return (<div style ={{padding:30}}>      {this.props.number}      <br/>      {this.props.array}      <br/>      {this.props.boolean.toString()}     </div>)     }}Son.propTypes = {  number:PropTypes.number,  array:PropTypes.array,  boolean:PropTypes.bool}class Father extends React.Component{ render(){   return (<Son      number = {'1'}      array = {'[1,2,3]'}      boolean = {'true'}      />)     }}

Then we can see the reported error. At this time, the reported error includes the wrong props attribute name, the wrong variable type, and the component name of the attribute, the expected correct variable type, the location of the error code, and other more detailed information.

This kind of "manual control" error reporting seems more friendly than general system error reporting.You can say: this error is my "Private Customization" (// warning //)

PropTypes can be used to detect all data type variables, including basic types of string, boolean, number, and reference types of objects, arrays, functions, and even new symbol types in ES6.

Son. propTypes = {optionalArray: PropTypes. array, // check the array type optionalBool: PropTypes. bool, // check the Boolean Type optionalFunc: PropTypes. func, // check Function (Function type) optionalNumber: PropTypes. number, // check the number optionalObject: PropTypes. object, // check the optionalString: PropTypes. string, // check string optionalSymbol: PropTypes. symbol, // the new symbol type in ES6}

[Note] the following are references from the official English documents. You can probably note that undefined and null are not listed in the five basic types. One of the shortcomings of propTypes type detection is, for undefined and null values, it cannot capture errors

Let's change the Father component in the above instance to the Son component:

class Father extends React.Component{ render(){  return (<Son     number = {null}     array = {null}     boolean = {null}    />)    }}

The result is that no error is reported on the output server (of course, the same effect is returned if you change it to undefined ).

3.2 use oneOfType to implement multiple-choice detection-specifying multiple data types that have been detected

In the previous example, the requirement for type detection is that a variable corresponds to a data type, that is, there is only one specified variable type. So how can we make it more flexible? For example, if multiple optional data types are specified to pass the test? The oneOfType method in PropTypes can do this. The oneOfType method receives an array of parameters and the array element is the data type you want to detect.

Import React from 'react 'import PropTypes from 'prop-types'; class Son extends react. component {render () {return (<div style = {padding: 30 }>{ this. props. number }</div>) }} Son. propTypes = {number: PropTypes. oneOfType ([PropTypes. string, PropTypes. number])} class Father extends React. component {render () {// respectively render the number 11 and the string 11 return (<div> <Son number = {'string 11'}/> <Son number = {11}/> </ div> )}}

At this time, because in the type detection, the number attribute specifies two types: string and number. Therefore, no error is reported on the console.

Of course, if you change to number = {array or another type of variable}, then an error will be reported.

3.3 Use oneOf to implement multi-choice detection-you can specify the values of multiple variables that pass the detection.

3.2 specifies multiple data types that can be detected. In the same way, we can specify the values of multiple variables that can be detected, this requires the oneOf method in PropTypes,Like the PropTypes method, the oneOf method receives an array of parameters, and the array element is the value of the variable you want to detect. For example, we change the part of the above type detection:

Son.propTypes = {  number:PropTypes.oneOf(     [12,13]   )}

The following error is reported during running:

3.4 arrayOf and objectOf implement multiple nested Detection

Imagine if we are detecting a variable of the basic type, it is naturally very simple, but what if we want to detect a variable of the reference type? In addition to checking whether the variable meets the specified reference type (Object/array), we also want to further check the attribute variables in the object or the data types of array elements, the above method alone cannot meet the requirements. At this time, we need to use the arrayOf and objectOf methods of PropTypes.

ArrayOf receives a parameter, which is the data type of the specified array element. The parameter received by objectOf is the data type of the attribute.

Modify the preceding example:

import React from 'react'import PropTypes from 'prop-types';class Son extends React.Component{ render(){  return (<div style ={{padding:30}}>    {this.props.array}    </div>)   }}Son.propTypes = {  array:PropTypes.arrayOf(PropTypes.number)}class Father extends React.Component{ render(){  return (<div>     <Son array = {[1,2,3,4]}/>    </div>)}}

After normal rendering, change <Son array = {[1, 3, 4]}/> to <Son array = {['1', '2', '3 ', '4']}/>, error reported

[Note] Although an error is reported, this does not affect the normal operation of the Program (for example, we can see that the rendering is still normal ), in essence, type detection reports a non-fatal error warning instead of a fatal error (the difference is whether the normal operation is affected ). The same applies to objectOf.

3.5 use the shape method to detect different data types of different properties of the target object

If you think about it seriously, you will find that the objectOf in 3.4 has a defect, that is, its internal attribute data type is forcibly defined as one, but usually an object should have multiple different types of attributes. In this case, objectOf does not meet the requirements. We should use the shape method. Its Usage:

PropTypes. shape ({attribute 1: Type 1, attribute 2: Type 2 ,//...}),

For example:

Import React from 'react 'import PropTypes from 'prop-types'; class Son extends react. component {render () {return (<div style = {padding: 30 }>{'my name is '+ this. props. object. name} <br/> {'My age is '+ this. props. object. age }</div>) }} Son. propTypes = {object: PropTypes. shape ({name: PropTypes. string, age: PropTypes. number})} class Father extends React. component {render () {return (<div> <Son object = {name: 'penghu Bay ', age: 20 }/></div> )}}

If no error is reported, change <Son object = {name: 'penghu Bay ', age: 20}/> to <Son object = {name: 'penghu Bay', age: '20'}/>, and then you can hear the error

3.6 use isRequired to check a required property in props (if this property does not exist, an error is returned)

Sometimes, when we perform a type check on a variable, we not only require it to conform to the expected type, but also require it to be written, at this time we need to use isRequired.

[Analysis]

Son.propTypes = {   number:PropTypes.number}

The purpose of this Code is to report an error when you write the number attribute in props and the number attribute type is incorrect. What if you do not write the number attribute at all? No error is reported. This is the necessity to use isRequired.

[Chestnut]

import React from 'react'import PropTypes from 'prop-types';class Son extends React.Component{ render(){  return (<div style ={{padding:30}}>     {this.props.number}    </div>)   }}Son.propTypes = {  number:PropTypes.number}class Father extends React.Component{ render(){  return (<div>    <Son />    </div>)  }}

No output in the console

If we change:

Son.propTypes = { number:PropTypes.number.isRequired}

Then we can see the error again:

[Note] Here is a question: number: PropTypes. number. isRequired, which requires the number to be a numeric type. But what if you don't want to control the number type but just want to control it? Is it written as number: isRequired or number: PropTypes. isRequired?Now PropTypes. any is on the stage! It indicates that the variable can be of any data type,So you can write -- number: PropTypes. any. isRequired

3.7 deal with more complex type detection-Write the property value of PropTypes into a function

Son. propTypes = {prop: function (props, propName, componentName) {if (/* judgment condition */) {return new Error (/* Incorrect Parameter */)}}}

In the Property prop type detection, the property value is a function. Here, props is the props object containing prop, propName is the property name of prop, and componentName is the component name of props, the Return Value of the function is an Error object.

Import React from 'react 'import PropTypes from 'prop-types'; class Son extends react. component {render () {return (<div style = {padding: 30 }>{ this. props. email} </div>)} Son. propTypes = {email: function (props, propName, componentName) {if (! /^ ([A-zA-Z0-9 _-]) + @ ([a-zA-Z0-9 _-]) + (. [a-zA-Z0-9 _-]) + /. test (props [propName]) {return new Error (the attribute in 'componentname + '+ propName +' does not conform to the mailbox format ');}}} class Father extends React. component {render () {return (<div> <Son email = {2314838004}/> </div> )}}

Here, we use a regular expression to check whether the email attribute passed to the Son component conforms to the email format. If the email attribute does not conform to the email format, an error is thrown, and 2314838004 obviously does not meet this requirement, so we get the demo below: (in fact, adding qq.com is my mailbox. Haha)

4. New types of detection in ES7:

It may seem strange to write propTypes outside the class. With the support of static class attributes of ES7, you can write as follows:

Class Son extends React. Component {static propTypes ={// .. type check} render () {return (/* rendering */)}}

But note that this takes effect in ES7

5. The independence of props-types and the discard of react. PropTypes

I used the independent third-party library props-types for type detection, but not long ago (react V15.5 before), it used react built-in type detection, instead of third-party libraries (that is, our current prop-types were originally separated based on the PropTypes object built in react)

Translated into Chinese:

So you can also perform type detection like this, although not recommended (to maintain downward compatibility, this is still available on the latest version of react)

Son.propTypes = { number:React.PropTypes.number}

6. References:

React official documentation/advanced guidance/type detection (docs/advanced guide/Typechecking with propTypes)

Https://facebook.github.io/react/docs/typechecking-with-proptypes.html

The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.