Detailed explanation of how components communicate in React

Detailed explanation of how components communicate in React

1. What is

We can split the communication between components into two words:

  • Components
  • Communications

Looking back at the Vue series of articles, components are one of the most powerful features of vue , and componentization is also the core idea of React

Compared with vue , React components are more flexible and diverse, and can be divided into many types of components in different ways.

Communication refers to the process by which a sender transmits information to a receiver in a certain format through a certain medium in order to achieve a certain purpose. In a broad sense, any information traffic is communication.

Communication between components means that components transmit information in some way to achieve a certain purpose.

2. How to communicate

There are many ways to transfer components, which can be divided into the following according to the sender and receiver:

  • Passing from parent component to child component
  • Child component passes to parent component
  • Communication between sibling components
  • Passing from parent component to descendant component
  • Non-relational component transfer

Passing from parent component to child component

Since the data flow of React is one-way, passing from parent component to child component is the most common way

When the parent component calls the child component, it only needs to pass parameters in the child component tag, and the child component can receive the parameters passed by the parent component through props attribute

function EmailInput(props) {
  return (
    <label>
      Email: <input value={props.email} />
    </label>
  );
}

const element = <EmailInput email="[email protected]" />;

Child component passes to parent component

The basic idea of ​​​​child component communication with parent component is that the parent component passes a function to the child component, and then gets the value passed by the child component through the callback of this function

The corresponding code of the parent component is as follows:

class Parents extends Component {
  constructor() {
    super();
    this.state = {
      price: 0
    };
  }

  getItemPrice(e) {
    this.setState({
      price:
    });
  }

  render() {
    return (
      <div>
        <div>price: {this.state.price}</div>
        {/* Pass a function into the child component*/}
        <Child getPrice={this.getItemPrice.bind(this)} />
      </div>
    );
  }
}

The corresponding code of the subcomponent is as follows:

class Child extends Component {
  clickGoods(e) {
    // Pass the value into this function this.props.getPrice(e);
  }

  render() {
    return (
      <div>
        <button onClick={this.clickGoods.bind(this, 100)}>goods1</button>
        <button onClick={this.clickGoods.bind(this, 1000)}>goods2</button>
      </div>
    );
  }
}

Communication between sibling components

If the data is transferred between sibling components, the parent component acts as an intermediate layer to achieve data intercommunication.

class Parent extends React.Component {
  constructor(props) {
    super(props)
    this.state = {count: 0}
  }
  setCount = () => {
    this.setState({count: this.state.count + 1})
  }
  render() {
    return (
      <div>
        <SiblingA
          count = {this.state.count}
        />
        <SiblingB
          onClick={this.setCount}
        />
      </div>
    );
  }
}

Passing from parent component to descendant component

It is a common thing for a parent component to pass data to its descendant components, just like global data.

Using context provides a way for components to communicate with each other, so that data can be shared and other data can read the corresponding data.

Create a context by using React.createContext

 const PriceContext = React.createContext('price')

After context is created successfully, Provider component exists under it to create the data source and Consumer component is used to receive data. The usage examples are as follows:

Provider component uses value attribute to pass data to descendant components:

<PriceContext.Provider value={100}>
</PriceContext.Provider>

If you want to get the data passed by Provider , you can receive it through the Consumer component or use contextType property, which are as follows:

class MyClass extends React.Component {
  static contextType = PriceContext;
  render() {
    let price = this.context;
    /* Perform rendering based on this value*/
  }
}

Consumer component:

<PriceContext.Consumer>
    { /* This is a function */ }
    {
        price => <div>price:{price}</div>
    }
</PriceContext.Consumer>

Non-relational component transfer

If the relationship between components is complex, it is recommended to manage the data as a global resource to achieve communication, such as redux . The use of redux will be described in detail later

Conclusion

Since React is a one-way data flow, the main idea is that components will not change the data they receive, but only listen for changes in the data. When the data changes, they will use the new value they received instead of modifying the existing value.

Therefore, it can be seen that during the communication process, the storage location of the data is stored in the parent location

This concludes this article about how components communicate in React. For more information about communication between React components, please search previous articles on 123WORDPRESS.COM or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • React parent-child component communication implementation method
  • The communication process between nested components and nested components in React
  • React component communication example
  • React data transfer method of internal communication between components
  • Detailed explanation of several ways of component communication in react
  • Detailed explanation of component communication in react

<<:  MySQL 8.0.17 installation graphic tutorial

>>:  Linux file/directory permissions and ownership management

Recommend

JavaScript anti-shake case study

principle The principle of anti-shake is: you can...

The whole process of IDEA integrating docker to deploy springboot project

Table of contents 1. IDEA downloads the docker pl...

Solution to 1045 error in mysql database

How to solve the problem of 1045 when the local d...

Detailed explanation of the solution to Tomcat's 404 error

The 404 problem occurs in the Tomcat test. The pr...

Summary of commonly used tool functions in Vue projects

Table of contents Preface 1. Custom focus command...

JavaScript Interview: How to implement array flattening method

Table of contents 1 What is array flattening? 2 A...

Vue echarts realizes horizontal bar chart

This article shares the specific code of vue echa...

MySQL Optimization: InnoDB Optimization

Study plans are easily interrupted and difficult ...

Docker installation and configuration steps for RabbitMQ

Table of contents Single-machine deployment Onlin...

Detailed example of mysql similar to oracle rownum writing

Rownum is a unique way of writing in Oracle. In O...

CSS to achieve scrolling image bar example code

On some websites, you can often see some pictures...