我可以使用什么方法将本机模块中的事件发送到React Native中的JS

时间:2016-07-12 10:19:33

标签: javascript reactjs react-native

根据React Native documentation,您可以使用sendAppEventWithName将本机代码中的事件发送给JS。但是在我的XCode中,代码建议告诉我这个方法已被弃用。

enter image description here

issue表示sendDeviceEventWithName应该有效但实际上它也已被弃用。

将事件发送给JS的实际方法是什么?

1 个答案:

答案 0 :(得分:6)

更新:请查看许多人提供了大量有用解决方案的this issue

我通过阅读其源代码来解决这个问题。使用RCTEventEmitter类。

MyModule.h

#import "RCTEventEmitter.h"
#import "RCTBridgeModule.h"

@interface MyModule : RCTEventEmitter <RCTBridgeModule>

@end

MyModule.m

@implementation MyModule

RCT_EXPORT_MODULE();

- (void)tellJS {
  [self sendEventWithName:@"sayHello" body:@"Hello"];
}

@end

因此,您可以通过调用sayHello方法向JavaScript发送名为Hello且数据为tellJS的事件。

在JavaScript方面,您必须使用NativeModules模块来获取此本机模块并将其包装在NativeEventEmitter类中,以便您可以接收事件。

import { NativeModules, NativeEventEmitter } from 'react-native'

const myModuleEvt = new NativeEventEmitter(NativeModules.MyModule)
myModuleEvt.addListener('sayHello', (data) => console.log(data))