react组件间通信

在根据需求实现业务的时候,我们经常会遇到组件间互相跳转和通信的问题,在具体实现业务逻辑的时候,我们会遇到各种组件间通信的情况,通过属性传递和props来解决组件间通信是比较常用的方法。

  • 父子

    • 父子向子组件通信 (属性传值)

      Parent.jsx

      import React, { Component } from 'react';
      
      import Child from './Child';
      
      class Parent extends Component {
          render() {
              return (
                  <div>
                      <Child name="testName" />
                  </div>
              );
          }
      }
      
      export default Parent;
      

      Child.jsx

      import React, { Component } from 'react';
      
      class Child extends Component {
          constructor(props){
              super(props);
          }
          render() {
              return (
                  <div>
                      <p>{this.props.name}</p>
                  </div>
              );
          }
      }
      
      export default Child;
      
    • 子组件向父组件通信 (回调父组件函数)

      Parent.jsx

      import React, { Component } from 'react';
      
      import Child from './Child';
      
      class Parent extends Component {
          constructor(props){
              super(props);
              this.state = {
                  name:''
              }
          }
          
          handleChange(name){
              this.setState({name});
          }
          
          render() {
              return (
                  <div>
                      <Child handleChange = {()=>this.handleChange}>{this.state.name}</Child>
                  </div>
              );
          }
      }
      
      export default Parent;
      

      Child.jsx

      import React, { Component } from 'react';
      
      class Child extends Component {
          constructor(props){
              super(props);
              this.state = {
                  name:''
              }
          }
          
          nameChange(e){
              let name = e.target.value;
              this.setState({name});
          }
          
          render() {
              return (
                <div>
                  <input onChange={()=>{this.nameChange}}/>
                  <button onclick={()=>{this.props.handleChange(this.state.name)}}>改变</button>
                </div>
              );
          }
      }
      
      export default Child;
      
  • 祖孙

    • 子组件向父组件的父组件通信 (回调父组件的父组件函数)

      类似于子组件向父组件通信,唯一的区别就是函数需要多传递一层

      —回调方法----->-----回调方法------>父的父

    • 当前组件向子组件的子组件通信(通过属性层层传递值)

      类似于父组件向子组件通信,唯一的区别就是属性值需要多传递一层

      父的父—属性值----->-----属性值------>

  • 兄弟

    • 兄弟组件间通信

      基本思路:一个子组件将数据通过回调函数的形式传递给父组件(共同),然后通过父组件(共同)传递给另外一个子组件

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值