React方向:兄弟组件的传值通信

1、兄弟组件A,兄弟组件B

A组件的值想传给兄弟组件B,需要在A组件和B组件的基础上建立公共的父组件common(名称自取),然后大致的步骤如下:

  • 1、common父组件将更新自身视图的方法传给A组件,A组件取到值后再通过调用父组件的的方法,并通过传参的形式,达到将A组件的值替换common组件自身的state状态的目的。
  • 2、common组件的state发生更改后,就再将更改后的值传给B组件,这样就实现了兄弟之间的组件通信。

2、详细步骤:

2.1、首先父组件将更新视图的方法传给A组件
   state = {
        inputValue:''
    }
  
    // 更新自身的视图
    handleUpdate = (inputValue) => {
        this.setState({
            inputValue
        })
    }

  <Abrother sendFn={this.handleUpdate}/>
2.2、A组件将值作为参数调取方法传给父组件

this.state.inputValue的值为A组件的状态state中的值

    // A组件将值作为参数调取方法传给父组件
    handleSend = () => {
        const {sendFn} = this.props;
        sendFn(this.state.inputValue)
    }
2.3、父组件再将state状态中的值传给B组件
  // B组件接收父组件传下来的值
  <Bbrother sendValue={this.state.inputValue}/>

测试代码:

组件A:

import React,{Component} from "react";

export default class Abrother extends Component {

    // 兄弟组件A需要将值先传给一个公共的父组件
    state = {
        inputValue:''
    }

    Astyle = {
        width:'500px',
        height:'200px',
        background:'skyblue'
    }

    spanStyle = {
        color:'red'
    }

    handleChange = (e)=>{
        console.log(e.target.value);
        this.setState({
            inputValue:e.target.value
        })
    }

    handleSend = () => {
        const {sendFn} = this.props;
        sendFn(this.state.inputValue)
    }

    render(){
        return(
            <>
               <div style={this.Astyle}>
                   <span style={this.spanStyle}>A组件</span>
                   <input type='text' value={this.state.inputValue} onChange={this.handleChange}></input>
                   <button onClick={this.handleSend}>发送A组件的值</button>
               </div>
            </>
        )
    }
}

组件B:

import React, {Component} from "react"

export default class Bbrother  extends Component {

    Bstyle = {
        width:'600px',
        height:'100px',
        marginTop:'50px',
        background:'#eee'
    }
    spanStyle = {
        color:'red'
    }

    render(){
        const { sendValue} = this.props;
        return (
            <div style={this.Bstyle}>
                <span style={this.spanStyle}>b组件</span>
                <h1>{ sendValue }</h1>
            </div>
        )
    }
}

公共父组件:

import React, {Component} from "react"
import Abrother from './Abrother'
import Bbrother from './Bbrother'

export default class common extends Component {
    // 公共的组件部分
    state = {
        inputValue:''
    }

    handleUpdate = (inputValue) => {
        this.setState({
            inputValue
        })
    }


    render(){
        return(
            <>
              <Abrother sendFn={this.handleUpdate}/>
              <Bbrother sendValue={this.state.inputValue}/>
            </>
        )
    }
}

效果图展示:

效果图.png

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容