Detailed explanation of data transmission between React parent components and child components

Detailed explanation of data transmission between React parent components and child components

Before learning the knowledge points of data transmission between React framework components, we need to clarify a few usage principles.

  1. Communication between React components is one-way. Data must be passed from parent to child or from child to parent layer by layer.
  2. If you want to pass data to sibling components, you must first pass it to the common parent and then pass it to the component location you want to pass it to.
  3. It is not recommended to use this layer-by-layer data transmission method to pass data between components that are not parent-child relationships; instead, choose to use the global state maintenance function module (Redux)

1. Parent component passes data to child component

The parent component passes data to the child component by setting the properties of the transferred data in the child component tag when referencing the child component in the parent component; and the child component receives the passed data through this.props; this realizes the data transmission from the parent component to the child component.

1.1. Parent component code

import React, { Component } from 'react';
import './App.css';
import Child from './child'
class App extends Component {
    constructor(props){
        super(props);
        this.state={
            msg:'parent class message',
            name:'John',
            age:99
        }
    }
    callback=(msg,name,age)=>{
        // setState method, modify the value of msg, the value is passed from child this.setState({msg});
        this.setState({name});
        this.setState({age});
    }
  render() {
    return (
      <div className="App">
        <p> Message: {this.state.msg}</p>
        <Child callback={this.callback} age={this.state.age} 
name={this.state.name}></Child>
      </div>
    );
  }
}
export default App;

Code description: When the parent component uses the child component (Child), it transfers two properties (age and name) and one method (callback is not considered for now) to the child component.

Key code:

<Child name={this.state.name} age={this.state.age}></Child>

1.2. Subcomponent code

import React from "react";
class Child extends React.Component{
    constructor(props){
        super(props);
        this.state={
            name:'Andy',
            age:31,
            msg:"Message from subclass"
        }
    }
    change=()=>{
        this.props.callback(this.state.msg,this.state.name,this.state.age);
    }
    render(){
        return(
            <div>
                <div>{this.props.name}</div>
                <div>{this.props.age}</div>
                <button onClick={this.change}>Click</button>
            </div>
        )
    }
}
export default Child;

Code description: In the child component, this.props is used directly in render to accept the data transmitted by the parent component and use it directly. It is not recommended that child components use this.setSate to process the received data.

Key code:

<div>{this.props.name}</div>
<div>{this.props.age}</div>

2. Subcomponents transfer data to parent components

In the React framework, data transmission from child components to parent components depends on the data transmission from parent components to child components. In fact, the parent component transfers the function of its own scope to the child component; the child component calls the function and transfers the data to be transmitted to the parent component in the form of function parameters.

2.1. Parent component code

In the code example above, a function is defined in the parent component and transferred to the child component.

class App extends Component {
......
    callback=(msg,name,age)=>{
        // setState method, modify the value of msg, the value is passed from child this.setState({msg});
        this.setState({name});
        this.setState({age});
    }
  render() {
    return (
      <div className="App">
        <Child callback={this.callback}></Child>
      </div>
    );
  }
}
export default App;

The parent component passes the function of its own scope to the child component. When the child component calls this function through this.props , it transfers the data to the group component through parameters.
Here the parent component has three parameters: msg, name, age; after the child component transfers the data, the parent component will process it using this.setState .

2.2. Subcomponent code

The child component receives the function transmitted from the parent component by using this.props; and calls this function through the parameter method to transmit data to the parent component.

class Child extends React.Component{
......
    change=()=>{
        this.props.callback(this.state.msg,this.state.name,this.state.age);
    }
    render(){
        return(
            <div>
                <button onClick={this.change}>Click</button>
            </div>
        )
    }
}
export default Child;

A method change() is created in the child component, which is bound to the click event onClick . change() method calls the this.props.callback() function (the function transmitted from the parent component). The actual parameter of the function is the data transmitted from the child component to the parent component.

The above is a detailed explanation of the data transmission between React parent components and child components. For more information about the data transmission between React parent components and child components, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • React Native reports "Cannot initialize a parameter of type''NSArray<id<RCTBridgeModule>>" error (solution)
  • Summary of react basics
  • Detailed explanation of the role of key in React
  • React entry-level detailed notes

<<:  Why should you be careful with Nginx's add_header directive?

>>:  How to recover accidentally deleted messages files in Linux

Recommend

Basic usage knowledge points of mini programs (very comprehensive, recommended!)

Table of contents What to do when registering an ...

How to fix the WeChat applet input jitter problem

Find the problem Let's look at the problem fi...

MySQL database terminal - common operation command codes

Table of contents 1. Add users 2. Change the user...

Introduction to fuzzy query method using instr in mysql

Using the internal function instr in MySQL can re...

How to control the startup order of docker compose services

summary Docker-compose can easily combine multipl...

Two ways to remove the 30-second ad code from Youku video

I believe everyone has had this feeling: watching ...

Summary of some efficient magic operators in JS

JavaScript now releases a new version every year,...

How to implement a simple HTML video player

This article introduces the method of implementin...

Design of pop-up windows and floating layers in web design

In the trend of gradual transition from tradition...

Interpretation of CocosCreator source code: engine startup and main loop

Table of contents Preface preparation Go! text St...

How to select all child elements and add styles to them in CSS

method: Take less in the actual project as an exa...

How to display div on object without being blocked by object animation

Today I made a menu button. When you move the mous...

Implementing circular scrolling list function based on Vue

Note: You need to give the parent container a hei...