5.3 组件之间的通讯

优质
小牛编辑
120浏览
2023-12-01

利用react的机制进行通信

  • ref属性

  <Text ref={(com)=>this.text = com} />
  • 父类更新子类
    • 父类把state作为属性传递给子类的props,任何时候state改变,会触发子类的componentWillUpdate

以下例子任何时候state的id改变,child里的componentWillUpdate会被触发

class ChildCom extends Component {
    render() {
        return (<View>这是子View,父级的state更改的时候,这里也会改变 {this.props.parentAttr}</View>);
    }
}

class myCom extends Component {
    render() {
        return <ChildCom parentAttr={this.state.id} >;
    }
}
  • 子类更新父类
    • 父类通过把需要被调用的方法传递给子类,子类需要操作父类的时候调用此方法
  <Child callback={this.callback.bind(this)} />

利用QAP的通信能力进行通信

  • 此种方法能解耦组件,即使没有继承关系的类,也能随意派发事件
这里增加QAP通信之间的例子,具体参考之羽的JSSDK