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

VUE+SpringBoot implements paging function

This article mainly introduces how to implement a...

Nginx Layer 4 Load Balancing Configuration Guide

1. Introduction to Layer 4 Load Balancing What is...

Detailed steps to install Hadoop cluster under Linux

Table of contents 1. Create a Hadoop directory in...

Vue realizes price calendar effect

This article example shares the specific code of ...

Detailed explanation of common usage of MySQL query conditions

This article uses examples to illustrate the comm...

Detailed explanation of overflow-scrolling to solve scrolling lag problem

Preface If you use the overflow: scroll attribute...

Vue practice of preventing multiple clicks

Generally, click events will be divided into diff...

Nginx high concurrency optimization practice

1. Necessity of Tuning​ I have always been reluct...

How to use Vue to develop public account web pages

Table of contents Project Background start Create...

Several situations where div is covered by iframe and their solutions

Similar structures: Copy code The code is as foll...

MySQL turns off password strength verification

About password strength verification: [root@mysql...

Vue Element front-end application development to obtain back-end data

Table of contents Overview 1. Acquisition and pro...