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

Detailed explanation of HTML onfocus gain focus and onblur lose focus events

HTML onfocus Event Attributes Definition and Usag...

Radio buttons and multiple-choice buttons are styled using images

I've seen people asking before, how to add sty...

Docker implements re-tagging and deleting the image of the original tag

The docker image id is unique and can physically ...

Detailed tutorial on building a private Git server on Linux

1. Server setup The remote repository is actually...

SELinux Getting Started

Back in the Kernel 2.6 era, a new security system...

When MySQL is upgraded to 5.7, WordPress reports error 1067 when importing data

I recently upgraded MySQL to 5.7, and WordPress r...

JavaScript deshaking and throttling examples

Table of contents Stabilization Throttling: Anti-...

Comprehensive website assessment solution

<br />Sometimes you may be asked questions l...

The difference between name and value in input tag

type is the control used for input and output in t...

Implementation of mysql data type conversion

1. Problem There is a table as shown below, we ne...

A brief discussion on the performance issues of MySQL paging limit

MySQL paging queries are usually implemented thro...