oc原生通知與rn通知是類似的:1妒潭、添加監(jiān)聽者 2、發(fā)通知 3旁振、組件被銷毀時移除監(jiān)聽者
rn與原生間同樣可以實現(xiàn)通知交互获询,比如oc發(fā)通知,rn來接收拐袜,并傳遞參數(shù)吉嚣。需要多做的一步是兩平臺之間建立橋接。
一:跨平臺建立橋接
#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調(diào)用RN
- (NSArray<NSString *> *)supportedEvents{
return @[@"sendValue"];
}
@end
二:交互橋接代碼已創(chuàng)建完畢蹬铺。接下來用oc發(fā)一條通知:
// 原生發(fā)通知 -> rn監(jiān)聽并重新渲染頁面
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中監(jiān)聽
NativeModules,
NativeEventEmitter
var RNBridgeModule = NativeModules.MineRNBridgeModule;
const myNativeEvt = new NativeEventEmitter(RNBridgeModule);
componentWillMount() {
this.listener = myNativeEvt.addListener('sendValue', this.receivedFilteData); //對應(yīng)了原生端的名字
},
componentWillUnmount() {
this.listener && this.listener.remove(); //記得remove哦
this.listener = null;
},
receivedFilteData(data) {//接受原生傳過來的數(shù)據(jù) 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);
}