在原生與js通訊時,用RCTEventEmitter,會遇到以下的坑
?bridge is not set. This is probably because you’ve explicitly synthesized the bridge
其原因由于RCTEventEmitter為nsobject對象巷屿,但卻不能像一般的NSObject對象一樣進行初始化漱贱,調(diào)用實例方法 治笨,以上錯誤出現(xiàn)在實例化了一個RCTEventEmitter類型的對象,并調(diào)用了他的實例方法贩虾,實際使用應(yīng)在addObserving等方法中進行實例方法的調(diào)用,而通過注冊通知來實現(xiàn)方法的調(diào)用蕉扮。
解決方法如下
@interface RNManager : RCTEventEmitter
+ (void)emitEventWithName:(NSString *)name andPayload:(NSDictionary *)payload;
@end
@implementation RNManager
RCT_EXPORT_MODULE()
- (void)startObserving {?
?[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(emitEventInternal:) name:@"event-emitted" object:nil];
}
- (void)stopObserving {?
?[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)emitEventInternal:(NSNotification *)notification{
?[self sendEventWithName:@"changeToken" body:notification.userInfo];
}
+ (void)emitEventWithName:(NSString *)name andPayload:(NSDictionary *)payload{ [[NSNotificationCenter defaultCenter] postNotificationName:@"event-emitted" object:self userInfo:payload];
}
- (NSArray*)supportedEvents {
return @[@"changeToken"];
}
- (void)changeToken:(NSString *)token {
[self sendEventWithName:@"changeToken" body:@{@"token" : token}];
}
@end
直接調(diào)用類方法整胃,在類方法中發(fā)內(nèi)部通知給對象就好了,這個通訊的對象在js代碼中會自動創(chuàng)建喳钟,不需要自身去創(chuàng)建的
JS代碼的實現(xiàn)如下
componentDidMount() {
constmyModuleEvt=newNativeEventEmitter(NativeModules.RNManager)
myModuleEvt.addListener('changeToken', (msg)=>{
console.log('i have recieve some ',msg)
})
}
這樣子就可以接受原生發(fā)過來的消息了