React component communication (parent-child component value transfer)

catalogue

1. Parent component to value child component

2. Child component value transfer parent component

3. Sibling component value transfer

4. Cross level component communication

summary

1. Parent component to value child component


When referring to a sub component, passing is equivalent to an attribute. For example, get the value of this param through porps.param in the sub component.

The parent component passes values to the child component, and the state of the parent component is passed to the child component through props.

Parent component code snippet:

constructor(props){
    super(props)
    this.state={
      message:"i am from parent"
    }
  }
  render(){
    return(
          <Child txt={this.state.message}/>
    )
  }
}

Sub component code snippet:

render(){
    return(
          <p>{this.props.txt}</p>
    )
}

Complete example

Create parent component   index.js

import React from 'react';
import ReactDOM from 'react-dom';
import User from './User';//Introducing sub components

//Define data
const person = {
    name: 'Tom',
    age:20
}

ReactDOM.render(
    //Render the subcomponent and pass the name and age attributes to the subcomponent
    <User name={person.name} age={person.age}></User>
    , document.getElementById('root'));

Create subcomponents   User.js

import React from 'react';

class User extends React.Component{
    render(){
        return (
            // Use the props attribute to receive the parameters passed by the parent component
            <div>{this.props.name},{this.props.age}</div>
        );
    }
}

export default User;

You can use the expand operator in the parent component  ...  Transfer object

index.js file

ReactDOM.render(
    //Render the subcomponent and pass the name and age attributes to the subcomponent
    <User {...person}></User>
    , document.getElementById('root'));

User.js file

render(){
   return (
       // Use the props attribute to receive the parameters passed by the parent component
       <div>{this.props.name},{this.props.age}</div>
   );
}



2. Child component value transfer parent component


A child component passes a message to the parent component by calling the method passed from the parent component to the child component. After the parent component receives the parameter, it assigns the value to the state of the parent component.

Complete case

Subcomponents   Son.js   File code example:

import React from 'react';

class Son extends React.Component {
    //Construction method
    constructor(){
        super();
        this.state = {
            inputValue:''
        }
    }
    //Button click event
    handleClick(){
        //Get the getdata method of the parent component through the props attribute and pass the value of this.state
        this.props.getdata(this.state.inputValue);
    }
    //Input box event to assign a value to this.state
    handleChange(e){
        this.setState({
            inputValue: e.target.value
        });
    }

    render(){
        return (
            <React.Fragment>
                <input onChange={this.handleChange.bind(this)}></input>
                <button onClick={this.handleClick.bind(this)}>Click to get data</button>
            </React.Fragment>
        );
    }

}

export default Son;

Parent component   Parent.js   File code example:

import React from 'react';
import Son from './Son';

class Parent extends React.Component {
    //Construction method
    constructor(){
        super();
        this.state = {
            mess: '' //Initialize the MES property
        }
    }
    //It is used to receive the value passing method of the sub component. The parameter is the value passed by the sub component
    getDatas(msg){
        //Assign the value passed by the subcomponent to the attribute in this.state
        this.setState({
            mess: msg
        });
    }

    render(){
        return (
            <React.Fragment>
                {/* Render subcomponents, set the access method of subcomponents,
                getdata The property name is called the parent component name in the child component. */}
                <Son getdata={this.getDatas.bind(this)}></Son>
                <div>Display data:{this.state.mess}</div>
            </React.Fragment>
        );
    }

}

export default Parent;

Entry file   index.js sample code:

import React from 'react';
import ReactDOM from 'react-dom';
import Parent from './Parent';

ReactDOM.render(<Parent></Parent>, document.getElementById('root'));



3. Sibling component value transfer


The value transfer between sibling components is performed through the parent component. The process is as follows:

Component A  –  Value transmission  -->  Parent component  –  Value transmission  -->  Component B

Code example:

establish   Acls.js   Component to provide data

import React from 'react';

class Acls extends React.Component {
	//Button click event to transfer value to parent component Pcls.js
    handleClick(){
        this.props.data("hello...React...");
    }

    render(){
        return (
            <button onClick={this.handleClick.bind(this)}>Acls Get data from component</button>
        );
    }
}

export default Acls;

Create parent component   Pcls.js   For transferring data

import React from 'react';
import Acls from './Acls';
import Bcls from './Bcls';

class Pcls extends React.Component {
	//Constructor
    constructor(){
        super();
        this.state = {
            mess: ''
        }
    }
	//The parameter of the value transfer method provided to the sub component Acls.js is the value passed from the obtained sub component
    getDatas(data){
        this.setState({
            mess: data
        });
    }

    render(){
        return (
            <React.Fragment>
                Pcls Display the button in the component and pass the value:
                <Acls data={this.getDatas.bind(this)}></Acls>
                <Bcls mess={this.state.mess}></Bcls>
            </React.Fragment>
        );
    }
}

export default Pcls;

Create subcomponents   Bcls.js   Used to show from   Acls.js   Data generated in component

import React from 'react';

class Bcls extends React.Component {

    render(){
        return (
            <div>stay Bcls Data displayed in component:{this.props.mess}</div>
        );
    }
}

export default Bcls;

4. Cross level component communication

Through context communication, we can imagine the relationship between components as a component tree. The original method is to pass the state down level by level through props and back level by level through calling methods. The other method is to set a region between them, which can be accessed by each component, which is equivalent to a global variable under the parent component.

code

Parent component at the top

class Index extends Component {
  static childContextTypes = {
    themeColor: PropTypes.string
  }

  constructor () {
    super()
    this.state = { themeColor: 'red' }
  }

  getChildContext () {
    return { themeColor: this.state.themeColor }
  }

  render () {
    return (
      <div>
        <Header />
        <Main />
      </div>
    )
  }
}

To set this context area in the parent component, set the name of the variable allowed to be accessed by child components in childContextTypes, and getChildContext () will set this area so that all child components can access the parameter themeColor

How are subcomponents accessed

class Title extends Component {
  static contextTypes = {
    themeColor: PropTypes.string
  }

  render () {
    return (
      <h1 style={{ color: this.context.themeColor }}>React.js Small book title</h1>
    )
  }
}

You can access it through this.context

summary

1. Parent component to value child component

         The state of the parent component is passed to the child component through props.

2. Child component value transfer parent component

         A child component passes a message to the parent component by calling the method passed from the parent component to the child component. After the parent component receives the parameter, it assigns the value to the state of the parent component.

3. Sibling component value transfer

         Component A  –  Value transmission  -->  Parent component  –  Value transmission  -->  Component B

        The parent component saves the parameters passed from component A into the state of the parent component, and then passes this state to component B.

4. Cross level component value transfer

         Communication through context is equivalent to a global variable under the parent component.

Tags: React redux

Posted on Mon, 20 Sep 2021 09:46:08 -0400 by catalin.1975