This is the 30th day of my participation in the August Text Challenge.More challenges in August

I. Introduction to props

When React encounters an element that is a user-defined component, it passes the JSX property to the component as a single object, called “props.”

The component declared by the function takes a props parameter to get the parameters passed by the property

function ComponentA(props) { 
    return <div>I am component B:{props. Value}</div>
}
Copy the code

This parameter must not be missing if a function component needs functions

When a Component extends its props parent class, it can pass properties using the this.props property name

class ComponentB extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
        return <div>I am component B {this.props. Name}</div>}}Copy the code

A derived subclass of the constructor class must call the super method, otherwise an error will be reported when creating a new instance.

This is because the subclass’s this object must be molded by the parent’s constructor to get the same instance attributes and methods as the parent, and then processed to add the subclass’s instance attributes and methods. If you don’t call super, your subclasses don’t get this.

Note: Props can pass any data type, and because props is read-only (a single data stream), all React components must use their props as if they were pure functions.

2. Batch pass props

Situation: Sometimes we want to pass more than one parameter, so if you write 10 of each parameter, maybe you can accept 100, 1000. Then your code is a miracle.

In this case, we borrow the expansion operator (…) from ES6. That’s three dots.

Let’s just define the parameters to pass, and then pass.

class Person extends React.Component {
    render() {
        console.log(this);  // Person instance object

        const { name, age, sex } = this.props;
        return (
            <ul>
                <li>Name: {name}</li>
                <li>Gender: {sex}</li>
                <li>Age: {age}</li>
            </ul>)}}// Single pass
ReactDOM.render(<Person name="Tom" age="18" sex="woman" />.document.getElementById('test'))
ReactDOM.render(<Person name="Jack" age="19" sex="man" />.document.getElementById('test1'))

// Batch pass
const p = { name: 'Lao wang'.age: 30.sex: 'man' }
ReactDOM.render(<Person {. p} / >.document.getElementById('test2'))

Copy the code

Iii. Verification of props

As applications grow larger, you usually want to have a specific value type for each props, and you can use type checking to catch a lot of errors, which makes development easier and reduces maintenance time. Check the props properties of the component. You need to configure the component’s special static propTypes property and implement prop validation with the prop-Types tripartite library. (Prop-types come with React scaffolding without downloading)

Way before version 16

ComponentA.propTypes = {
    name: React.PropTypes.string.isRequired, // Restrict name to a string
}
Copy the code

After version 16, it is used as a separate library

  1. Set propTypes to the class of the class component
import React, {Component} from 'react'
import PropTypes from 'prop-types'

class ComponentA extends Component {
    render() {
        // Because the JSX element is essentially called implicitly by react.createElement ()
        // So if your js file contains JSX elements, you must import React to allow JSX elements to be called implicitly or the compiler will fail
        // 'React' must be in scope when using JSX
        return (
            <div>
                <p>name: {this.props.name}</p>
                <p>age: {this.props.age}</p>
            </div>
        )
    }
}

ComponentA.propTypes = {
    name: PropTypes.string,
    age: PropTypes.number
}

export default ComponentA
Copy the code
  1. Use the classStatic property syntax (static)Set propTypes,The class itselfAttributes added.
import React, {Component} from 'react'
import PropTypes from 'prop-types'

class ComponentA extends Component {

    static propTypes = {
        name: PropTypes.string,
        age: PropTypes.number
    }

    render() {
        // Because the JSX element is essentially called implicitly by react.createElement ()
        // So if your js file contains JSX elements, you must import React to allow JSX elements to be called implicitly or the compiler will fail
        // 'React' must be in scope when using JSX
        return (
            <div>
                <p>name: {this.props.name}</p>
                <p>age: {this.props.age}</p>
            </div>)}}export default ComponentA
Copy the code
  1. Default property value, which you define when a property is not passed
// Specify the default tag attribute value
Person.defaultProps = { 
    sex: 'male'.age: 17 
}
Copy the code
  1. Function components support component props validation by setting properties to constructors
import React, {Component} from 'react'
import PropTypes from 'prop-types'

class ComponentA extends Component {

    static propTypes = {
        name: PropTypes.string,
        age: PropTypes.number
    }

    render() {
        // Because the JSX element is essentially called implicitly by react.createElement ()
        // So if your js file contains JSX elements, you must import React to allow JSX elements to be called implicitly or the compiler will fail
        // 'React' must be in scope when using JSX
        return (
            <div>
                <p>name: {this.props.name}</p>
                <p>age: {this.props.age}</p>
            </div>)}}export default ComponentA
Copy the code

Constructors and props in class components

If state is not initialized or method binding is not performed, there is no need to implement a constructor for the React component.

Before the React component is mounted, its constructor is called. When implementing a constructor for a react.componentsubclass, you should call super(props) before any other statements. Otherwise, this. Props might have undefined bugs in the constructor.

In general, constructors in React are used only in two cases:

  • Initialize internal state by assigning an object to this.state.
  • Bind an instance of the event handler (bind changes this to point)
// Basic use of state

constructor(props) {
    super(props);
    // Initialization state
    this.state = {
      isHot: true.wind: 'the wind'
    }
    // bind: does two things ---- generates a new function and changes this to an instance object of Weather
    // This. ChangeWeather is a prototype method. Bind this to generate a new method on the instance itself, resulting in a changeWeather method on the instance itself, so that it can be called
    this.changeWeather = this.changeWeather.bind(this);  
}
Copy the code

The difference between props or not

class Person extends React.Component {

    // 1, pass props and also pass super
  constructor(props) {
    // console.log(props)
    super(props);
    console.log(this.props);  // All props passed to the component such as :{name: "Tom", sex: "male ", age: 17, speak: ƒ}
  }

  // 2, pass props but not super
  constructor(props) {
    // console.log(props)
    super(a);console.log(this.props); // undefined
    console.log(props); // All props passed to the component such as :{name: "Tom", sex: "male ", age: 17, speak: ƒ}
  }

  // 3
  constructor() {
    // console.log(props)
    super(a);console.log(this.props); // undefined}}Copy the code

Conclusion:

Whether the constructor receives props and passes it to super depends on whether you want to access props through this in the constructor

5. Use of prop-types in tripartite library

Basic type validation

PropTypesDemo.propTypes = {
    propsArray: PropTypes.array, / / array
    propsObject: PropTypes.object, / / object
    propsString: PropTypes.string, / / string
    propsNumber: PropTypes.number, / / digital
    propsBool: PropTypes.bool, / / a Boolean value
    propsSymbol: PropTypes.symbol, // Private data type
    propsFunc: PropTypes.func, / / function
    // Node data type (any data type that can be rendered)
    propsNode: PropTypes.node,
    // React element (JSX)
    propsElement: PropTypes.element,
}	
Copy the code

React objects bool symbol func are not renderable directly on the page. These data types are not node types

The attribute modifier isRequired is passed

All prop-types can be followed by the isRequired modifier to indicate that the property isRequired

PropTypesDemo.propTypes = {
    propsArray: PropTypes.array.isRequired, // Mandatory Array type
    propsElement: PropTypes.element.isRequired // The element type is mandatory
    propsAny: PropTypes.any.isRequired // Any data type must be passed
}
Copy the code

Prop-types also provides an any data type for any data type, which, in conjunction with the isRequired modifier, indicates that the current property cannot be null

Complex type validation

PropTypesDemo.propTypes = {
    // Data is an instance of the specified constructor function
    propsCurrentProto: PropTypes.instanceOf(Dog),
    // The attribute value is one of the specified values
    propsOneOf: PropTypes.oneOf(['male'.'woman']),
    The data type of the property is one of the specified types
    propsOneOfType: PropTypes.oneOfType([
            PropTypes.array,
            PropTypes.object,
            PropTypes.instanceOf(RegExp),
    PropTypes.oneOf(['male'.'woman']]),// Specify an array for each data type
   propsStringArray: PropTypes.arrayOf(PropTypes.string),
    // Specifies an object of the value data type for each entry
    propsDateObj: PropTypes.objectOf(PropTypes.instanceOf(Date)),
        // Specify objects of the key and value data types
    propsCurrentObject: PropTypes.shape({
            name: PropTypes.string, // This property can be the default value
               age: PropTypes.number.isRequired // This property must exist in the current object})}Copy the code

Several validation rules besides instanceOf and oneOf can be nested with each other, and the isRequired modifier can still be used in the validation rules described above

Custom authentication rules

In the React component’s propTypes property, you can set an authentication function to implement custom authentication rules for specified attributes. Custom validation functions generally accept three parameters: props, propName, and componentName.

  • Props: The set of objects for which the current component receives attribute passes

  • PropName: Use the property name of the current custom rule

  • ComponentName: Indicates the name of the current component

Just return an Error instance object outside the function when the receiving props property value does not pass the validation rule.

Example: To implement custom authentication rules, the data to be imported must be a string or a number. The string cannot contain FXXK sensitive characters and the number must be between 18 and 120.

ComponentC.propTypes = {
    propsA: function (props, propName, componentName) {
        let val = props[propName]
        if(typeof val === 'string') {
             if(/fxxk/.test(val)) {
                return  new Error(` components:${componentName}, middle attribute"${propName}"The value of${val}Contains sensitive characters')}}else if(typeof val === 'number') {
            if(val < 18 || val > 120) {return  new Error(` components:${componentName}, middle attribute"${propName}"The value of${val}Does not meet the range of 18-120 ')}}else {
            return new Error(` components:${componentName}, middle attribute"${propName}"Values are not strings or numbers)}}}Copy the code

Define validation rules to be used with arrayOf or ObjectOf

Custom validation functions can be passed as arguments to arrayOf or ObjectOf of prop-Types library to iterate over arrays and objects. The validation rule function takes five arguments: propValue, key, componentName, Location, and propsFullName

  • PropValue: The array or object itself that is being validated

  • Key: Traverses the index of a number group or the key value of an object

  • ComponentName: Indicates the name of the current component

  • Location: Position constant of the current value “prop”

  • PropsFullName: The full name of the string iterated over the current item

Examples: propsCustomArrayOf[2], propsCustomArrayOf. Name

PropTypesDemo.propTypes = {
    // arrayOf or ObjectOf custom validation rules
    propsCustomArrayOf: PropTypes.arrayOf(function (propValue, key, componentName, location, propsFullName) {
        if(!/matchme/.test(propValue[key])) {
                     return new Error(`Failed prop type: Invalid prop '${propsFullName}' supplied to ${componentName}.Validation failed.`)}}),propsCustomObjectOf: PropTypes.objectOf(function (propValue, key, componentName, location, propsFullName) {
        if(!/matchme/.test(propValue[key])) {
                     return new Error(`Failed prop type: Invalid prop '${propsFullName}' supplied to ${componentName}.Validation failed.`})}}),Copy the code

Six, summary

  1. Each component object has the props(short for properties) property

  2. All properties of component tags are stored in props

  3. Changing data is passed from component to component through label properties

  4. Note: Do not modify the props data inside the component

  5. Prop validation using the propTypes property with the prop-types tripartite library (no additional download, integrated in scaffolding)