This is the 14th day of my participation in the August More Text Challenge. For details, see:August is more challenging

How do React components communicate with each other?

What is it

We can split intercomponent communication into two words:

  • component
  • communication

Reviewing the Vue series, components are one of the most powerful features in Vue, and componentization is 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

And communication refers to the sender through a certain media in a certain format to deliver information to the receiver to achieve a certain purpose, in a broad sense, any information traffic is communication

Communication between components means that components communicate information in a certain way to achieve a certain purpose

How to communicate

Components can be delivered in a variety of ways, which can be classified as follows according to the sender and receiver:

  • Parent component passes to child component
  • Child components are passed to parent components
  • Communication between sibling components
  • The parent component is passed to the descendant component
  • Non-relational component delivery

Parent component passes to child component

Since React’s data flow is one-way, parent to child is the most common way

When a parent component calls a child component, it only needs to pass the parameters in the child component tag. The child component can receive the parameters passed by the parent component using the props property

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

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

Child components are passed to parent components

The basic idea of a child component communicating with a parent component is that the parent component passes a function to the child component, and then receives the value passed by the child component through the callback of the function

The corresponding code of the parent component is as follows:

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

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

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

The corresponding code of the child component is as follows:

class Child extends Component {
  clickGoods(e) {
    // Pass the value in 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>); }}Copy the code

Communication between sibling components

If it is passed between sibling components, the parent component acts as the middle layer to realize the intercommunication of data, passing through the use of the parent component

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>); }}Copy the code

The parent component is passed to the descendant component

It is most common for a parent component to pass data to its descendants, just like global data

Using context provides a way for components to communicate with each other, sharing data and allowing other data to read the corresponding data

Create a context by using React. CreateContext

 const PriceContext = React.createContext('price')
Copy the code

After the context is successfully created, the Provider component is used to create data sources and the Consumer component is used to receive data. The following is an example:

The Provider component uses the value property to pass data to its descendants:

<PriceContext.Provider value={100}>
</PriceContext.Provider>
Copy the code

If you want to retrieve the data passed by the Provider, you can either use the Consumer component or use the contextType attribute, which corresponds to the following:

class MyClass extends React.Component {
  static contextType = PriceContext;
  render() {
    let price = this.context;
    /* Render work based on this value */}}Copy the code

Consumer component:

<PriceContext.Consumer>
    { /* Here is a function */ }
    {
        price= > <div>Price: {price}</div>
    }
</PriceContext.Consumer>
Copy the code

Non-relational component delivery

In the case of complex relationship types between components, it is recommended that the data be managed in a global resource for communication, such as Redux. More on the use of redux later

Third, summary

Since React is a one-way data stream, the main idea is that components don’t change the data they receive, they just listen for changes, and when the data changes, they use the new value they receive instead of modifying the existing value

Therefore, it can be seen that during the communication, data is stored in the superior location