Detailed explanation of component communication in react

Detailed explanation of component communication in react

Parent component communicates with child components

  • The parent component passes its state to the child component, and the child component receives it as a property. When the parent component changes its state, the property received by the child component will change
  • The parent component uses ref to mark the child component, and changes the state of the child component by calling the child component's method. The parent component can also call the child component's method.

Define ref reference in parent group

import React,{Component,createRef} from 'react'
import Child1 from './Child1'
export default class App extends Component {
    constructor(props){
        super(props)
        this.child = createRef()
    }
    render(){
        return(
            <div>
                <Child1 ref={this.child}/>
                <button onClick={this.fn.bind(this)}></button>
            </div>
        )
    }
    fn(){
        const child = this.child.current
        child.setTitle()
    }
}

Subcomponent defines the data source and how to modify the data source

import React,{Component} from 'react'
export default class Child1 extends Component{
    state={
        title:'Title'
    }
    render(){
        return (
            <div>
                {this.state.title}
            </div>
        )
    }
    setTitle(){
        this.setstate({title:'hh'})
    }
}

Child components communicate with parent components

The parent component passes one of its own methods to the child component. You can do anything in the method, such as changing the state. The child component receives the parent component's method through this.props and calls it.

Cross-component communication

React does not have an event bus like Vue to solve this problem. One way is to use their common parent component to implement it through proxy, but the process will be quite cumbersome. React provides Context to achieve cross-component communication without having to explicitly pass props through each layer of the component tree.

Complex non-parent-child component communication is difficult to handle in react, and data sharing between multiple components is also difficult to handle. In actual work, we will use flux, redux, and mobx to implement

Ancestors and descendants

  1. Define the store class to export Provider, COnsumer in createContext
  2. Publish a message in the ancestor node: Provider value = any data
  3. Subscribe in descendant nodes: Consumer callback function {value=>(component)}
    1. Define the data source store
    store.js
import React , {createContext} from 'react'
let {Provider, Consumer} = createContext()
export { 
    Provider, //Publish Consumer //Subscribe}

2. Ancestor Node

import React ,{Component} from 'react'
import {Provider,Consumer} from './store'
import Son from './Son'
export default class App extends Component {
    constructor(props){
        super(props)
        this.state={
            name:'mingcen'
        }
    }
    render(){
        return (
            <div>
                <Provider value={this.state.name}>
                    <Son/>
                </Provider>
            </div>
        )
    }
}

3. Descendant nodes

import React,{Component} from'react'
import {Consumer} from './store'
export default class Son1 extends Component{
    constructor(props){
        super(props)
        this.state={
            name:'uuu'
        }
    }
    render(){
        return(
            <div>
                <Consumer>
                   {
                        value=>{
                            <div>{value.name}</div>
                        }
                   }
                </Consumer>
            </div>
        )
    }
}

Brother node communication

  • A child object is attached to the event
  • Another one hanging on the properties
  • By changing the properties of another component, you can change the content accepted by another component.

ancestor

state={
    count:1,
    setCount:()=>{
        this.setState(state=>{
            return {
                count:++state.count
            }
        })
    }
}
render(){
    let {count,setCount} = this.state
    return(
        <div>
            <Provider value={{count,setCount}}>
                <Cmp1></Cmp1>
                <Cmp2></Cmp2>
            </Provider>
        </div>
    )
}

Brother Cmp2

import React, { Component , createContext } from 'react'
export default class Cmp2 extends Component {
  // Only got the default data --> not wrapped in the Provider component static contextType = createContext
  render() {
    return (
      <div>
        <button onClick={this.setCount.bind(this)}>Auto-increment data</button>
      </div>
    )
  }
  setCount() {
    this.context.setCount()
  }
}

Brother Cmp1

<Consumer>
    {
        value => <h3>{value.count}</h3>
    }
</Consumer>

Summarize

This article ends here. I hope it can be helpful to you. I also hope that you can pay more attention to more content on 123WORDPRESS.COM!

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
  • React development tutorial: Communication between React components
  • Detailed explanation of component communication issues in React
  • Example code for communication between React components
  • Three ways to communicate between React components (simple and easy to use)

<<:  Markup language - specify CSS styles for text

>>:  Analysis of the usage of Xmeter API interface testing tool

Recommend

Several solutions for CSS record text icon alignment

It is very common to see images and text displaye...

How to quickly build a static website on Alibaba Cloud

Preface: As a junior programmer, I dream of build...

Implementation of Docker deployment of MySQL cluster

Disadvantages of single-node database Large-scale...

Linux debugging tools that developers and operators must look at [Recommended]

System performance expert Brendan D. Gregg update...

Practice of implementing custom search bar and clearing search events in avue

Table of contents 1. Customize the search bar con...

Reasons and methods for Waiting for table metadata lock in MySQL

When MySQL performs DDL operations such as alter ...

Vue implements login type switching

This article example shares the specific code of ...

Query process and optimization method of (JOIN/ORDER BY) statement in MySQL

The EXPLAIN statement is introduced in MySQL quer...

Two ways to install Python3 on Linux servers

First method Alibaba Cloud and Baidu Cloud server...

CentOS method to modify the default ssh port number example

The default ssh port number of Linux servers is g...

A brief introduction to the usage of decimal type in MySQL

The floating-point types supported in MySQL are F...

Vue3 Vue Event Handling Guide

Table of contents 1. Basic event handling 2. Send...