1.在原生頁面
#import "RCTEventEmitter.h"
#import "RCTBridgeModule.h"
#import "RCTBridge.h"
@interface iOSExport : RCTEventEmitter <RCTBridgeModule>
+(void)callPostNoti:(NSMutableDictionary *)dic;
@end
#import "iOSExport.h"
@implementation iOSExport
@synthesize bridge=_bridge;
RCT_EXPORT_MODULE(iOSExport)
- (NSArray<NSString *> *)supportedEvents
{
return @[@"EventReminder"];
}
RCT_EXPORT_METHOD(startObserving)
{
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(handleNotification:) name:@"postLocation" object:nil];
}
+(void)callPostNoti:(NSMutableDictionary *)dic
{
[[NSNotificationCenter defaultCenter]postNotificationName:@"postLocation" object:dic];
}
-(void)handleNotification:(NSNotification *)noti
{
[self sendEventWithName:@"EventReminder" body:noti.object];
}
@end
2.在js頁面
import {
NativeModules,
NativeEventEmitter,
} from 'react-native';
//開始監(jiān)聽
var iOSExport = NativeModules.iOSExport
iOSExport.startObserving()
var emitter = new NativeEventEmitter(iOSExport);
//用獲取的模塊創(chuàng)建監(jiān)聽器
this.subScription = emitter.addListener("EventReminder", (body) => {
console.info('收到', body)
this.subScription.remove()
})