think icon indicating copy to clipboard operation
think copied to clipboard

React Native组件间通信

Open bytemofan opened this issue 6 years ago • 0 comments

React Native中组件通信方式有三种:

  • props
  • state
  • RCTDeviceEventEmitter

RCTDeviceEventEmitter主要是用于完全没有直接父子关系的多个组件之间的通信。类似发布订阅模式的使用方式。

无论是接收方和发送事件的一方都要引入这个模块:

import RCTDeviceEventEmitter from 'RCTDeviceEventEmitter' ;

发布一个事件:

RCTDeviceEventEmitter.emit('事件名',value);  

接收(订阅)一个事件:

componentDidMount(){  
  this.listener = RCTDeviceEventEmitter.addListener('事件名',(value)=>{  
       // 接受到通知后的处理  
  });  
}  
  
componentWillUnmount(){  
  // 一定要记得移除  
  this.listener.remove();  
}

RCTDeviceEventEmitter还可以和native端通信。

bytemofan avatar Sep 06 '18 12:09 bytemofan