iOS 向ReactNative 發(fā)送通知事件
[self.bridge.eventDispatcher sendAppEventWithName:@"EventReminder_BarcodeScanSuccessForRN"
的時(shí)候會(huì)提示
'sendDeviceEventWithName:body:'is deprecated: SubclassRCTEventEmitterinstead
查看源碼發(fā)現(xiàn),DeviceEventEmitter 和NativeAppEventEmitter 均已經(jīng)被遺棄。
DeviceEventEmitter源碼描述
/**
* Deprecated - subclass NativeEventEmitter to create granular event modules instead of
* adding all event listeners directly to RCTDeviceEventEmitter.
*/
NativeAppEventEmitter源碼描述
/**
* Deprecated - subclass NativeEventEmitter to create granular event modules instead of
* adding all event listeners directly to RCTNativeAppEventEmitter.
*/
同時(shí)都推薦使用NativeEventEmitter子類
在0.28版本之后,iOS向Js端發(fā)射消息的 思路如下
Natived端,新版本模塊類頭文件必須繼承自RCTEventEmitter
1.-(NSArray *)supportedEvents;中設(shè)置所支持的通知的名稱
2.- (void)startObserving; Native端開(kāi)啟通知
3.RN使用NativeEventEmitter.addListener模塊監(jiān)聽(tīng)通知
4.RN在 componentWillUnmount 中remove移除通知
5.- (void)stopObserving Native端移除通知
Native部分
.h
#import "RCTEventEmitter.h"
@interface MallManageAPI : RCTEventEmitter <RCTBridgeModule>
.m
-(NSArray *)supportedEvents {
return@[@"EventReminder_CollectionProductSuccessForRN"];
}
- (void)startObserving {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(CollectionProductSuccessForRNAction:)
name:@"CollectionProductSuccessForRN"
object:nil];
}
- (void)CollectionProductSuccessForRNAction:(NSNotification*)notification {
dispatch_async(dispatch_get_main_queue(), ^{
[self sendEventWithName:@"EventReminder_CollectionProductSuccessForRN" body:nil];
});
}
- (void)stopObserving {
[[NSNotificationCenterdefaultCenter]removeObserver:selfname:@"CollectionProductSuccessForRN"object:nil];
}
RN部分
import React, { Component } from 'react';
import {
NativeModules,
Platform,
//NativeAppEventEmitter,
NativeEventEmitter
} from 'react-native';
var NativeModulesByIOS = NativeModules.MallManageAPI;
const NativeNotificationMoudule = new NativeEventEmitter(NativeModulesByIOS)
componentWillMount() {
console.log('開(kāi)始訂閱通知...');
if (Platform.OS === 'ios') {
subscription = NativeNotificationMoudule.addListener(
'EventReminder_CollectionProductSuccessForRN',
(reminder) => {
this._onRefresh()
}
);
} else {
}
}
componentWillUnmount() {
if (Platform.OS === 'ios') {
subscription.remove();
} else {
}
}