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

Rhit efficient visualization Nginx log viewing tool

Table of contents Introduction Install Display Fi...

React hooks pros and cons

Table of contents Preface advantage: shortcoming:...

How to create a file system in a Linux partition or logical volume

Preface Learn to create a file system on your sys...

MySQL intercepts the sql statement of the string function

1. left(name,4) intercepts the 4 characters on th...

The difference between Display, Visibility, Opacity, rgba and z-index: -1 in CSS

We often need to control the hidden, transparent ...

js implements clock component based on canvas

Canvas has always been an indispensable tag eleme...

How to use javascript to do simple algorithms

Table of contents 1 Question 2 Methods 3 Experime...

js to achieve floor scrolling effect

This article uses jQuery to implement the sliding...

Solution to running out of MySQL's auto-increment ID (primary key)

There are many types of auto-increment IDs used i...

Solution to the problem of invalid line-height setting in CSS

About the invalid line-height setting in CSS Let&...

A brief discussion on the correct posture of Tomcat memory configuration

1. Background Although I have read many blogs or ...

How to understand SELinux under Linux

Table of contents 1. Introduction to SELinux 2. B...