react组件之间的几种通信情况

组件之间的几种通信情况

  • 父组件向子组件通信
  • 子组件向父组件通信
  • 跨级组件通信
  • 没有嵌套关系组件之间的通信

1,父组件向子组件传递

React数据流动是单向的,父组件向子组件通信也是最常见的;父组件通过props向子组件传递需要的信息

在引用子组件的时候传递,相当于一个属性,例如:

复制代码
//父组件
class
Parent extends Component{ state = { msg: 'start' }; render() { return <Child parms={this.state.msg} />; //父组件引用子组件时,将state状态数据以属性的方式传递给子组件props对象的parms属性中 } } //子组件 class Child extends Component{
  constructor(...args){
    super(...args); //调用父类的 constructor(x, y),继承父组件的this对象,这是因为子类没有自己的this对象,而是继承父类的this对象,
              //只有render时,可以不用写,在render函数以外要使用this,就得调用super()方法
  }

  render() {
    return <p>{this.props.parms}</p> //子组件通过this.props.parms使用父组件传递过来的值
 } }
复制代码

 

2,子组件向父组件传递

  • 利用回调函数
  • 利用自定义事件机制

子组件通过 调用父组件传递到子组件的方法  让父组件自己去修改自己的状态值。

父组件向子组件传递函数:

     <Child parm={this.state.msg} transMsg={msg=>this.transMsg(msg)}/>
   <Child name={this.state.name} parent={this} /> //将整个this传递给子组件
 

子组件调用父组件函数:
this.props.transMsg(parms);

this.props.parent.fn(666);//子组件使用props.parent的整个父组件可以任意调用父组件下的函数

完整代码:

复制代码
class Parent extends Component{
 
    constructor(props) {
        super(props);
        state = {
            msg: 'start'
        };
    }
    transMsg(types){
        var newOrders = [];
        for(let type of types){
            if(type)
            alert(type);
        }
        
      }
  render() {
    return <Child parms={this.state.msg} />;
  }
}
class Child extends Component{
    
     constructor(props) {
        super(props);
        // call parent component
        console.log("parms :",this.props.parms);
       this.props.transMsg("hi ~~");
    }
  render() {
    return <p>{this.props.parms}</p>
  }
}
复制代码

 


 
 
posted @   maxlove  阅读(2992)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示