Home Web Front-end Front-end Q&A What are the methods of react communication?

What are the methods of react communication?

Mar 22, 2022 pm 02:33 PM
react communication

React communication methods include: 1. Use props for parent-child component communication; 2. Use callback functions for child-parent component communication; 3. Use variable promotion for sibling component communication; 4. Use Context for cross-component communication; 5. Use node’s events module for single instance communication; 6. Use redux to share data communication.

What are the methods of react communication?

The operating environment of this tutorial: Windows7 system, react17.0.1 version, Dell G3 computer.

Six communication methods of React

1. Props parent-child communication
2. Callback function, child-father communication
3 .Variable promotion, sibling component communication
4.Context, cross-component communication
5.Single instance communication of node’s events module
6.redux shared data communication

1.propsFather-child communication

function Children(props) {
      return (
        <div>
          <p>Children</p>
          <p>{props.text}</p>
        </div>
      )
    }
    function Parent() {
      return (
        <div>
          <p>Parent</p>
          <Children text="这是爸爸传给你的东西"></Children>
        </div>
      )
    }
    
    export default Parent
Copy after login

2.Callback function, child-parent communication

function Children(props) {
  return (
    <div>
      <p>Children</p>
      <p>{props.text}</p>
      <button onClick={() => { props.handleChange(&#39;改变了&#39;) }}>
        点击我改变爸爸传给我的东西
      </button>
    </div>
  )
}

function Parent() {
  let [text, setText] = useState(&#39;这是爸爸传给你的东西&#39;)
  function handleChange(val) {
    setText(val)
  }
  return (
    <div>
      <p>Parent</p>
      <Children handleChange={handleChange} text={text}></Children>
    </div>
  )
}
export default Parent
Copy after login

3. Variable promotion, communication among brothers

function Children(props) {
  return (
    <div>
      <p>Children</p>
      <button onClick={() => { props.setText(&#39;我是Children发的信息&#39;) }}>给Children1发信息</button>
    </div>
  )
}
function Children1(props) {
  return (
    <div>
      <p>Children1</p>
      <p>{props.text}</p>
    </div>
  )
}

function App() {
  let [text, setText] = useState(&#39;&#39;)
  return (
    <>
      <div>APP</div>
      <Children setText={setText}></Children>
      <Children1 text={text}></Children1>
    </>
  )
}
export default App
Copy after login

4.Context, communication across groups

Old way of writing

class Children extends React.Component {
  static contextTypes = {
    text: PropsType.string
  }
  render() {
    return (
      <div>
        <p>Children</p>
        <p>{this.context.text}</p>
      </div>
    )
  }
}

class Parent extends React.Component {
  static childContextTypes = {
    text: PropsType.string
  }
  getChildContext() {
    return {
      text: &#39;我是爸爸的信息&#39;
    }
  }
  render() {
    return (
        <div>
          <p>Parent</p>
          <Children></Children>
        </div>
    )
  }
}
export default Parent
Copy after login

New way of writing

const { Consumer, Provider } = React.createContext()

class Children extends React.Component {
  render() {
    return (
      <Consumer>
        {
          (value) => (
            <div>
              <p>Children1</p>
              <p>{value.text}</p>
            </div>
          )
        }
      </Consumer>
    )
  }
}

class Parent extends React.Component {
  render() {
    return (
      <Provider value={{ text: &#39;我是context&#39; }}>
        <div>
          <p>Parent</p>
          <Children1></Children1>
        </div>
      </Provider>
    )
  }
}

export default Parent
Copy after login

5.Single instance communication of the events module of node

function Children(props) {
  return (
    <div>
      <p>Children</p>
      <p>{props.text}</p>
      <button onClick={() => { props.event.emit(&#39;foo&#39;) }}>点击我改变爸爸传给我的东西</button>
    </div>
  )
}

function Parent() {
  let [text, setText] = useState(&#39;这是爸爸传给你的东西&#39;)
  let event = new Events()
  event.on(&#39;foo&#39;, () => { setText(&#39;改变了&#39;) })
  return (
    <div>
      <p>Parent</p>
      <Children event={event} text={text}></Children>
    </div>
  )
}
export default Parent
Copy after login

Note⚠️: For this kind of communication, remember to introduce the events module at the top, no need to install, node its own module.

6.redux shared data communication

store.js

import { createStore } from &#39;redux&#39;

let defaultState = {
    text: &#39;我是store&#39;
}

let reducer = (state = defaultState, action) => {
    switch (action) {
        default: return state
    }
}

export default createStore(reducer)
Copy after login

child.js

import React from &#39;react&#39;

import { connect } from &#39;react-redux&#39;

class Child extends React.Component {
    render() {
        return (
            <div>Child<p>{this.props.text}</p></div>
        )
    }
}

let mapStataToProps = (state) => {
    return {
        text: state.text
    }
}

export default connect(mapStataToProps, null)(Child)
Copy after login

Parent.js

class Parent extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <div>
          <p>Parent</p>
          <Child></Child>
        </div>
      </Provider>
    )
  }
}

export default Parent
Copy after login

Note: Remember to install redux and react-redux.

[Related recommendations: Redis video tutorial]

The above is the detailed content of What are the methods of react communication?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end Sep 28, 2023 am 10:48 AM

React front-end and back-end separation guide: How to achieve front-end and back-end decoupling and independent deployment, specific code examples are required In today's web development environment, front-end and back-end separation has become a trend. By separating front-end and back-end code, development work can be made more flexible, efficient, and facilitate team collaboration. This article will introduce how to use React to achieve front-end and back-end separation, thereby achieving the goals of decoupling and independent deployment. First, we need to understand what front-end and back-end separation is. In the traditional web development model, the front-end and back-end are coupled

New generation of optical fiber broadband technology - 50G PON New generation of optical fiber broadband technology - 50G PON Apr 20, 2024 pm 09:22 PM

In the previous article (link), Xiao Zaojun introduced the development history of broadband technology from ISDN, xDSL to 10GPON. Today, let’s talk about the upcoming new generation of optical fiber broadband technology-50GPON. █F5G and F5G-A Before introducing 50GPON, let’s talk about F5G and F5G-A. In February 2020, ETSI (European Telecommunications Standards Institute) promoted a fixed communication network technology system based on 10GPON+FTTR, Wi-Fi6, 200G optical transmission/aggregation, OXC and other technologies, and named it F5G. That is, the fifth generation fixed network communication technology (The5thgenerationFixednetworks). F5G is a fixed network

How to build a reliable messaging app with React and RabbitMQ How to build a reliable messaging app with React and RabbitMQ Sep 28, 2023 pm 08:24 PM

How to build a reliable messaging application with React and RabbitMQ Introduction: Modern applications need to support reliable messaging to achieve features such as real-time updates and data synchronization. React is a popular JavaScript library for building user interfaces, while RabbitMQ is a reliable messaging middleware. This article will introduce how to combine React and RabbitMQ to build a reliable messaging application, and provide specific code examples. RabbitMQ overview:

React Router User Guide: How to implement front-end routing control React Router User Guide: How to implement front-end routing control Sep 29, 2023 pm 05:45 PM

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

The development history of wireless mice The development history of wireless mice Jun 12, 2024 pm 08:52 PM

Original title: "How does a wireless mouse become wireless?" 》Wireless mice have gradually become a standard feature of today’s office computers. From now on, we no longer have to drag long cords around. But, how does a wireless mouse work? Today we will learn about the development history of the No.1 wireless mouse. Did you know that the wireless mouse is now 40 years old? In 1984, Logitech developed the world's first wireless mouse, but this wireless mouse used infrared as a The signal carrier is said to look like the picture below, but later failed due to performance reasons. It was not until ten years later in 1994 that Logitech finally successfully developed a wireless mouse that works at 27MHz. This 27MHz frequency also became the wireless mouse for a long time.

How to build real-time data processing applications using React and Apache Kafka How to build real-time data processing applications using React and Apache Kafka Sep 27, 2023 pm 02:25 PM

How to use React and Apache Kafka to build real-time data processing applications Introduction: With the rise of big data and real-time data processing, building real-time data processing applications has become the pursuit of many developers. The combination of React, a popular front-end framework, and Apache Kafka, a high-performance distributed messaging system, can help us build real-time data processing applications. This article will introduce how to use React and Apache Kafka to build real-time data processing applications, and

PHP, Vue and React: How to choose the most suitable front-end framework? PHP, Vue and React: How to choose the most suitable front-end framework? Mar 15, 2024 pm 05:48 PM

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

Integration of Java framework and front-end React framework Integration of Java framework and front-end React framework Jun 01, 2024 pm 03:16 PM

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

See all articles