Detailed explanation of React component communication

Detailed explanation of React component communication

Component Communication Introduction

content

  • A component is an independent and closed unit, and by default, can only use its own data.
  • In the componentization process, we split a complete function into multiple components to better complete the functionality of the entire application.
  • In this process, it is inevitable that multiple components share some data.
  • In order to realize these functions, it is necessary to break the independence and closedness of components and allow them to communicate with the outside world. This process is component communication.

Three ways

  • Between parent and child components
  • Between sibling components
  • Across component levels

summary

The state in a component is private, that is, the state of a component can only be used inside the component and cannot be used directly outside the component

Component Communication - Father to Son

content:

  • The parent component provides the state data to be passed
  • Add attributes to the subcomponent tag, with the value being the data in the state
  • The child component receives the data passed from the parent component through props

Core code

The parent component provides data and passes it to the child component

class Parent extends React.Component {
    state = { lastName: '王' }
    render() {
        return (
            <div>
                Pass data to child components: <Child name={this.state.lastName} />
            </div>
        )
    }
}

Subcomponent receives data

function Child(props) {
	return <div>The child component receives data: {props.name}</div>
}

Component communication - child to parent

Ideas

Using the callback function, the parent component provides the callback, the child component calls it, and the data to be passed is used as the parameter of the callback function.

step

1. Parent component

1. Define a callback function f (which will be used to receive data)

2. Pass the function f as the value of the attribute to the child component

2. Subcomponents

1. Get f through props

2. Call f and pass in the data of the child component

Core code

The parent component provides a function and passes it to the child component

class Parent extends React.Component {
    state: {
      num: 100
    }
    f = (num) => {
        console.log('Subcomponent data received', num)
    }
    render() {
        return (
            <div>
            	Child component: <Child f={this.f} />
            </div>
        )
    }
}

The child component receives the function and calls

class Child extends React.Component {
    handleClick = () => {
      // Call the props passed in by the parent component and pass in the parameter this.props.f(100)
    }
    return (
    	<button onClick={this.handleClick}>Click me to pass data to the parent component</button>
    )
}

summary

Child to parent: Call the method defined in the parent component in the child component and pass in parameters as needed

Component Communication-Brother Components

In React, there is no such thing as a sibling component, there is only state promotion.

Ideas

  • Promote the shared state to the nearest common parent component, which manages the state
  • Thoughts: State Improvement
  • Common parent component responsibilities:
    • Providing shared state
    • Provides methods for manipulating shared state
  • The child components that want to communicate only need to receive the state or the method to operate the state through props

Core code

parent.js

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import Jack from './Jack'
import Rose from './Rose'
class App extends Component {
  // 1. The state is promoted to the parent component state = {
    msg: '',
  }
  render() {
    return (
      <div>
        <h1>I am an App component</h1>
        <Jack say={this.changeMsg}></Jack>
        {/* 2. Display the status to the child component*/}
        <Rose msg={this.state.msg}></Rose>
      </div>
    )
  }
  changeMsg = (msg) => {
    this.setState({
      msg,
    })
  }
}
// Rendering component ReactDOM.render(<App />, document.getElementById('root'))

Son1.js

import React, { Component } from 'react'
export default class Jack extends Component {
  render() {
    return (
      <div>
        <h3>I am Jack component</h3>
        <button onClick={this.say}>Say</button>
      </div>
    )
  }
  say = () => {
    this.props.say('you jump i look')
  }
}

Son2.js

import React, { Component } from 'react'
export default class Rose extends Component {
  render() {
    return (
      <div>
        <h3>I am the Rose component - {this.props.msg}</h3>
      </div>
    )
  }
}

Component communication - cross-level component communication

If you want to use cross-level component communication in Vue, you need to use Context

Steps to use Context

There are three steps:

1. Import and call the createContext method to deconstruct the Provider and Consumer components from the result

import { createContext } from 'react'
const { Provider, Consumer } = createContext()

2. Use the Provider component to wrap the root component and provide the data to be shared through the value attribute

return (
  <Provider value={Put the data to be passed here}>
  	<Contents of the root component/>
  </Provider>
)

3. In any descendant component, wrap the entire component with the Consumer component exported in step 2

return (
	<Consumer>
  	{
      (data) => {
      	// The parameter data here will automatically receive the data passed in by the Provider // console.log(data)
      	return <component content>
    	}
    }
  </Consumer>
)

Landing code

Create context.js file

import { createContext } from 'react'
const { Provider, Consumer } = createContext()
export { Consumer, Provider }

Transforming the root component

import { Provider } from './context'
render () {
    return (
      <Provider value={{ num: this.state.num }}>
        <div>
          Root component, num: {this.state.num}
          <Parent />
          <Uncle />
        </div>
      </Provider>
    )
  }

Transform the descendant component Uncle.js

import React from 'react'
import { Consumer } from './context'
export default class Uncle extends React.Component {
  render () {
    return (
      <Consumer>
        {(data) => {
          return <div>I am Uncle component, {data.num}</div>
        }}
      </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:
  • Detailed explanation of react component communication methods (multiple)
  • React communication props between parent and child components
  • react.js parent-child component data binding real-time communication example code

<<:  Web design must have purpose, ideas, thoughts and persistence

>>:  10 skills that make front-end developers worth millions

Recommend

Various problems encountered in sending emails on Alibaba Cloud Centos6.X

Preface: I have newly installed an Alibaba cloud ...

How to create LVM for XFS file system in Ubuntu

Preface lvm (Logical Volume Manager) logical volu...

Zabbix monitors mysql instance method

1. Monitoring planning Before creating a monitori...

Installation and use of mysql on Ubuntu (general version)

Regardless of which version of Ubuntu, installing...

How to implement JavaScript's new operator yourself

Table of contents Constructor new Operator Implem...

Bootstrap3.0 study notes table related

This article mainly explains tables, which are no...

Where is the project location deployed by IntelliJ IDEA using Tomcat?

After IntelliJ IDEA deploys a Javaweb project usi...

Detailed explanation of MySQL file storage

What is a file system We know that storage engine...

Vue3 slot usage summary

Table of contents 1. Introduction to v-slot 2. An...

Vue encapsulates the public function method of exporting Excel data

vue+element UI encapsulates a public function to ...

Detailed tutorial for downloading and installing mysql8.0.21

Official website address: https://www.mysql.com/ ...

Vue implements user login switching

This article example shares the specific code of ...

CentOS 6.5 installation mysql5.7 tutorial

1. New Features MySQL 5.7 is an exciting mileston...