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

Details on how to write react in a vue project

We can create jsx/tsx files directly The project ...

JS operation object array to achieve add, delete, modify and query example code

1. Introduction Recently, I helped a friend to ma...

Vue.set() and this.$set() usage and difference

When we use Vue for development, we may encounter...

MySQL 8.0.23 Major Updates (New Features)

Author: Guan Changlong is a DBA in the Delivery S...

Solve the problem that the docker container cannot ping the external network

Today, when I was building a redis environment in...

Linux completely removes node.js and reinstalls it through the yum command

first step Delete it once with the built-in packa...

Tutorial on how to install and use Ceph distributed software under Linux

Table of contents Preface 1. Basic Environment 1....

How to open external network access rights for mysql

As shown below: Mainly execute authorization comm...

MySQL learning database search statement DQL Xiaobai chapter

Table of contents 1. Simple retrieval of data 2. ...

Sharing some details about MySQL indexes

A few days ago, a colleague asked me a question a...

MySQL database operations and data types

Table of contents 1. Database Operation 1.1 Displ...

Detailed explanation of samba + OPENldap to build a file sharing server

Here I use samba (file sharing service) v4.9.1 + ...

Vue implements login jump

This article example shares the specific code of ...