一、ReactNative内部事件通知
1.引入头文件
import { DeviceEventEmitter } from 'react-native';
2.发送方 发送通知
DeviceEventEmitter.emit('通知名称');
3.接收方 接收通知
componentDidMount() {
this.subscription = DeviceEventEmitter.addListener('通知名称', (params) => {
});
}
4.接收方 清除通知
componentWillUnmount() {
this.subscription && this.subscription.remove();
}
二、ReactNative与iOS原生通知
1.原生生成管理类,如 ‘CallManager’,并继承 RCTEventEmitter,一般和模块类共用,所以遵守RCTBridgeModule协议。
@interface CallManager : RCTEventEmitter<RCTBridgeModule>
@end
2.在原生需要通知RN的地方,发送事件,如:发送peerNumber。
NSDictionary *dic = @{@"peerNumber":peerNumber};
[self sendEventWithName:@"CallIncoming" body:dic];
3.在原生中实现supportedEvents方法 ,返回事件名称数组。
-(NSArray<NSString *> *)supportedEvents {
return @[@"CallIncoming"];
}
4.在RN中,添加头文件。
import { NativeModules, NativeEventEmitter } from 'react-native';
5.在RN中,获取CallManager管理类,并创建监听对象。
var callManager = NativeModules.CallManager;
const subscribeStreamEvt = new NativeEventEmitter(callManager);
6.在RN中,添加监听,并实现_callIncoming方法。
componentDidMount() {
this.listener = subscribeStreamEvt.addListener('CallIncoming', this._callIncoming.bind(this));
}
_callIncoming(data) {
}
7.在RN中清除监听。
componentWillUnmount() {
this.listener && this.listener.remove();
this.listener = null;
}