Value passing between React Hook components and React class components passing values [sibling components + parent-child components]

一、 React Hook

1-1 Passing values ​​from the parent component to the child component (props)

  1. Anything that the parent component wants to pass can be passed to the child component through props.

    • For example: variables, functions, jsx components, etc.
import React, {
    
     useState } from 'react';

// 父组件
const PropsCom = () => {
    
    
   const [name, setName] = useState('niutt');

   return (
       <div>
           <h2>父组件</h2>
           {
    
    /* 这里是重要代码,向子组件传递parentName这个prop,值为name变量 */}
           <ChildrenCom parentName={
    
    name} />
       </div>
   );
};

// 子组件
const ChildrenCom = (props) => (
   <div>
       <h4>子组件</h4>
       <p>获取父组件传过来的值:{
    
    props.parentName}</p>
   </div>
);

export default PropsCom;


1-2 Grandpa passes value to grandson between groups (context)

Use context to achieve cross-component value transfer

  1. const value = useContext(MyContext);

    • useContext takes a context object (the return value of React.createContext) and returns the current value of the context.
    • The current context value <MyContext.Provider>is determined by the value prop closest to the current component in the upper component.

1-2-2 Example:

Please add a picture description

1. First, we create a new createContext.js file (convenient for expansion and reference)

// createContext.js文件
import {
    
     createContext } from 'react';

const myContext = createContext(null);

export default myContext;


2. Write the following code in the index.js file (our top-level Test component)

import React, {
    
     useReducer } from 'react';
import {
    
     Button } from 'antd';

import myContext from './createContext';
import BrotherTest from './BrotherTest';

const reducer = (state, action) => {
    
    
    const [type, payload] = action;
    switch (type) {
    
    
        case 'set':
            return {
    
    
                ...state,
                ...payload,
            };
        default:
            return {
    
    
                ...state,
                ...payload,
            };
    }
};

const initData = {
    
    
    count: 0,
    text: 'Text-顶层组件',
};

const Test = () => {
    
    
    const [state, dispatch] = useReducer(reducer, initData);

    return (
        <div style={
    
    {
    
     backgroundColor: '#f2f2f2' }}>
            <h1>
                Test最顶层组件----实现跨组件间传值。
            </h1>
            <Button
                onClick={
    
    () => {
    
    
                    dispatch(['set', {
    
     count: state.count + 1 }]);
                }}
            >
                点我修改count
            </Button>
            <Button
                onClick={
    
    () => {
    
    
                    dispatch([
                        'set',
                        {
    
     text: '最顶层组件Test修改了自己的text---' },
                    ]);
                }}
            >
                点我修改text
            </Button>
            <br />
            Test组件的最顶层组件----count:{
    
    state.count}
            <br />
            Test组件的最顶层组件----text:{
    
    state.text}
            <br />
            <myContext.Provider value={
    
    {
    
    
                count: state.count,
                text: state.text,
                // 把最顶层Test组件的dispatch传递下去给后代组件,这样后代组件就都能修改最顶层组件的数据了。
                proDispatch: dispatch,
            }}
            >
                {
    
    /* 子组件 */}
                <BrotherTest />
            </myContext.Provider>
        </div>
    );
};

export default Test;


  1. Write the following code in BrotherTest.js and InTest.js files
    • As you can see from the screenshot, through the context context, we can achieve value transfer and operations across components, without the need to pass values ​​through props layer by layer.
      insert image description here

1-3 Transfer value between subgroups to parent component (parent component props pass callback function)

Similar to Vue: [Vue Basic 9] – passing values ​​between parent and child components

  1. If the child component wants to pass certain values ​​to the parent component, or the child component wants to execute a certain piece of logic in the parent component after executing a certain piece of logic, then you can write the corresponding logic function in the parent component and pass this through props The function can be called to the subcomponent.
import React, {
    
     useState } from 'react';
import {
    
     Button } from 'antd';

// 父组件
const CallbackCom = () => {
    
    
    const [count, setCount] = useState(0);

    // 获取子组件传过来的value值并设置到count,val参数就是子组件的value值
    const getChildrenValue = (val) => {
    
    
        setCount(val);
    };

    return (
        <div>
            <h2>父组件</h2>
            <p>获取子组件传过来的值:{
    
    count}</p>
            {
    
    /* 这里是重要代码,向子组件传递getValue这个prop,它的值是一个回调函数 */}
            <ChildrenCom getValue={
    
    getChildrenValue} />
        </div>
    );
};

// 子组件
const ChildrenCom = (props) => {
    
    
    const [value, setValue] = useState(0);

    const addValue = () => {
    
    
        setValue(value + 1);
        // 向父组件传递每次递增的value值
        props.getValue(value + 1);
    };

    return (
        <div>
            <h4>子组件</h4>
            <Button onClick={
    
    addValue}>点击改变子组件的value值:{
    
    value}</Button>
        </div>
    );
};

export default CallbackCom;


Two, React class component value passing

2-1 brother pass value

Use event event bus in react

  • I posted it directly below, so that I can read the article when the time comes, haha

①: First install the events plugin

  • npm install events --save

②: Create a new file, and then import events, which is equivalent to the Bus in Vue

Please add a picture description

③: accept parameter sibling components

The following syntax is deprecated:

Please add a picture description

Change it to the following:

Please add a picture description

④: Brother component that triggers the monitoring event to pass parameters

Please add a picture description

2-2 Father-son communication

Same idea as functional components

2-2-1 father -----> child

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

Please add a picture description

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

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

  1. full example
    • Create parent component index.js
import React from 'react';
import ReactDOM from 'react-dom';
import User from './User';//引入子组件

//定义数据
const person = {
    
    
    name: 'Tom',
    age:20
}

ReactDOM.render(
    //渲染子组件,并向子组件传递name,age属性
    <User name={
    
    person.name} age={
    
    person.age}></User>
    , document.getElementById('root'));

  • Create subcomponent User.js
import React from 'react';

class User extends React.Component{
    
    
    render(){
    
    
        return (
            // 使用props属性接收父组件传递过来的参数
            <div>{
    
    this.props.name}{
    
    this.props.age}</div>
        );
    }
}

export default User;

2-2-2 Child -----> Parent (passing callback function type props)

Child components pass messages to parent components by calling methods passed from parent components to child components.

Please add a picture description

  1. SubcomponentSon.js
import React from 'react';

class Son extends React.Component {
    
    
    //构造方法
    constructor(){
    
    
        super();
        this.state = {
    
    
            inputValue:''
        }
    }
    //按钮点击事件
    handleClick(){
    
    
        //通过props属性获取父组件的getdata方法,并将this.state值传递过去
        this.props.getdata(this.state.inputValue);
    }
    //输入框事件,用于为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)}>点击获取数据</button>
            </React.Fragment>
        );
    }

}

export default Son;

  1. Parent.js
import React from 'react';
import Son from './Son';

class Parent extends React.Component {
    
    
    //构造方法
    constructor(){
    
    
        super();
        this.state = {
    
    
            mess: '' //初始化mess属性
        }
    }
    //用于接收子组件的传值方法,参数为子组件传递过来的值
    getDatas(msg){
    
    
        //把子组件传递过来的值赋给this.state中的属性
        this.setState({
    
    
            mess: msg
        });
    }

    render(){
    
    
        return (
            <React.Fragment>
                {
    
    /* 渲染子组件,设置子组件访问的方法,
                getdata属性名为子组件中调用的父组件方法名 */}
                <Son getdata={
    
    this.getDatas.bind(this)}></Son>
                <div>展示数据:{
    
    this.state.mess}</div>
            </React.Fragment>
        );
    }

}

export default Parent;

  1. 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'));

2-2-3 Passing values ​​between sibling groups

Son -----> Father -----> Son, if you have other methods, you can tell them in the comment area~~~

Guess you like

Origin blog.csdn.net/hannah2233/article/details/128547619