Detailed explanation of the use of props in React's three major attributes

Detailed explanation of the use of props in React's three major attributes

In the last issue, we talked about state. Next, let’s talk about props. The function of props is to communicate between components (parent-child components). First, let’s talk about its usage in various components:

Class Component

//Parent component value passing class Father extends React.PureComponent{
    render(){
        return (
            <Son value={"son"} />
        )
    }
}

class Son extends React.PureComponent{
    render(){
        return (
            <div>this data is {this.props.value}</div>
        )
    }
}

Functional Components

function Fa(){
    return (
        <Son value={"son"} />
    )
}

function Son(props){
    return (
        <div>this data is {props.value}</div>
    )
}

In a function component, props only needs to pass a value, which is very convenient. In the React documentation, the explanation of props is

When a React element is a user-defined component, it converts the attributes and children received by JSX into a single object and passes it to the component. This object is called "props"

Therefore, we can get the value uploaded by the parent component through props, and we can also directly get the child component written in jsx through props.children

Props are read-only

React emphasizes in the documentation

All React components must protect their props from being mutated, just like pure functions.

We have already explained the concept of pure functions in redux. In short, we cannot change the value of props.

Inter-component communication

Now let's summarize the communication between components:

  • props First, let’s write a class component:
// We have already talked about passing values ​​from parent components to child components. Now let's summarize how child components pass values ​​to parent components. At this time, the parent component often needs to pass a props function to the child component first. The child component changes the value of the parent component by calling the passed function export default class Fa extends Component {
    state = {faValue:'Fa1'}

    changeFa = (value)=>{
        this.setState(()=>{
            return {faValue:value}
        })
    }
    render() {
        return (
            <>
                <h1>Fa's value is {this.state.faValue}</h1>
                <Son changeFa={this.changeFa}/>
            </>
        )
    }
}

export default class Son extends React.PureComponent{

    changeValue = ()=>{
        this.props.changeFa(this.inputRef.value)
    }
    render() {
        return (
            <>
                <input type="text" placeholder={"Please enter your value"} ref={(el)=>{this.inputRef = el}}/>
                <button onClick={this.changeValue}>change</button>
            </>
        )
    }
}

Then write a function component:

function Fa(){
    const [faValue,setFaValue] = useState("Fa1")

    const changeFa = (value)=>{
        setFaValue(value)
    }
    return (
        <div>
            <h1>Fa's value is {faValue}</h1>
            <Son changeFa={changeFa} />
        </div>
    )
}

function Son(props){
    const inputValue = useRef("")
        //Define a function to change the value of the fa component const changeFaValue = ()=>{
            props.changeFa(inputValue.current.value)
        }
        return (
            <>
                <input type="text" placeholder={"Please enter the value you want to change"} ref={inputValue}/>
                <button onClick={changeFaValue}>change value</button>
            </>
        )
}
  • eventbus (subscribe-publish mechanism)

This can be understood as a weakened redux. Here we use the library pubsub-js to write it. The writing method is as follows:

//For example, for the previous input case, I need to pass a value to the brother component. If we don't use props, how should we write Bro:
export default class Bro extends Component {

    componentDidMount() {
        this.sonData = PubSub.subscribe("brother",(msg,data)=>{
            console.log("Bro Component have received the msg",data);
        })
    }

    componentWillUnmount() {
        PubSub.unsubscribe(this.sonData)
    }

    render() {
        return (
            <>
                <div>brother</div>
            </>
        )
    }
}
Son:
export default class Son extends React.PureComponent{

    changeValue = ()=>{
        PubSub.publish("brother",this.inputRef.value)
    }

    render() {
        return (
            <>
                <input type="text" placeholder={"Please enter your value"} ref={(el)=>{this.inputRef = el}}/>
                <button onClick={this.changeValue}>change</button>
            </>
        )
    }
}

This method commonly uses three APIs. The first one is subscribe, which publishes the corresponding event and defines what to do with the event. The second is publish, which subscribes to published events and passes in the corresponding values ​​to be changed. The third one is unsubscribe, which is used to cancel the publishing and optimize the memory.

The above is the detailed content of the detailed explanation of the use of props, one of the three major attributes of React. For more information about props, one of the three major attributes of React, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • In-depth understanding of the three core properties of React
  • How to deeply understand React's ref attribute
  • Detailed explanation of the use of Refs in React's three major attributes
  • Detailed explanation of the use of state in React's three major attributes
  • Do you know the three major properties of React?

<<:  Sequence implementation method based on MySQL

>>:  How to implement Docker volume mounting

Recommend

Detailed code for implementing 3D tag cloud in Vue

Preview: Code: Page Sections: <template> &l...

Vue implements simple production of counter

This article example shares the simple implementa...

Can MySQL's repeatable read level solve phantom reads?

introduction When I was learning more about datab...

jQuery achieves fade-in and fade-out effects

Before using jQuery to complete the fade-in and f...

10 skills that make front-end developers worth millions

The skills that front-end developers need to mast...

MySQL series multi-table join query 92 and 99 syntax examples detailed tutorial

Table of contents 1. Cartesian product phenomenon...

How to draw a mind map in a mini program

Table of contents What is a mind map? How to draw...

Implementation of dynamic particle background plugin for Vue login page

Table of contents The dynamic particle effects ar...

Javascript to achieve drumming effect

This article shares the specific code of Javascri...

HTML discount price calculation implementation principle and script code

Copy code The code is as follows: <!DOCTYPE HT...

MySQL horizontal and vertical table conversion operation implementation method

This article uses examples to illustrate how to i...

Detailed explanation of CSS3 Flex elastic layout example code

1. Basic Concepts //Any container can be specifie...

Summary of javascript date tools

let Utils = { /** * Is it the year of death? * @r...