oc原生通知与rn通知是类似的:1、添加监听者 2、发通知 3、组件被销毁时移除监听者
rn与原生间同样可以实现通知交互,比如oc发通知,rn来接收,并传递参数。需要多做的一步是两平台之间建立桥接。
一:跨平台建立桥接
#import "RCTBridgeModule.h"
#import "RCTEventEmitter.h"
#import "RCTBridge.h"
#import "RCTEventDispatcher.h"
@interface MineRNBridgeModule : RCTEventEmitter<RCTBridgeModule>
@end
#import "MineRNBridgeModule.h"
#import "AppDelegate.h"
@implementation MineRNBridgeModule{
NSDictionary *_resourceFilter;
}
- (instancetype)init{
self = [super init];
if (self) {
//资源筛选通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendValue:) name:@"source" object:nil];
}
return self;
}
@synthesize bridge = _bridge;
RCT_EXPORT_MODULE(MineRNBridgeModule);
RCT_EXPORT_METHOD(LoadSourceData){
[self sendValue:nil];
}
-(void)sendValue:(NSNotification *)notification {
// NSDictionary *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"source"];
NSDictionary *data = notification.object;
[self sendEventWithName:@"sendValue"
body:data];
}
//OC调用RN
- (NSArray<NSString *> *)supportedEvents{
return @[@"sendValue"];
}
@end
二:交互桥接代码已创建完毕。接下来用oc发一条通知:
// 原生发通知 -> rn监听并重新渲染页面
NSDictionary *filterData = @{
@"publicIndex" : @(publicIndex),
@"isReset" : @(isReset),
@"index1" : @(index1),
@"index2" : @(index2),
@"index3" : @(index3),
@"index4" : @(index4),
@"index5" : @(index5),
@"chapter" : chapter,
};
[[NSUserDefaults standardUserDefaults] setObject:filterData forKey:@"source"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"source" object:filterData];
三:在rn中监听
NativeModules,
NativeEventEmitter
var RNBridgeModule = NativeModules.MineRNBridgeModule;
const myNativeEvt = new NativeEventEmitter(RNBridgeModule);
componentWillMount() {
this.listener = myNativeEvt.addListener('sendValue', this.receivedFilteData); //对应了原生端的名字
},
componentWillUnmount() {
this.listener && this.listener.remove(); //记得remove哦
this.listener = null;
},
receivedFilteData(data) {//接受原生传过来的数据 data={code:,result:}
if (data != null) {
this.state.fliterData = data;
this.state.publicIndex = data.publicIndex;
this.state.chapterId = data.chapter;
this.onRefresh();
//alert(this.state.publicIndex);
}
网友评论