DeviceEventEmitter与NativeAppEventEmitter

Rub*_*bys 18 react-native deviceeventemitter

我想使用事件在本机ios/android和我的本机应用程序之间进行通信.

我看到两种方法:DeviceEventEmitter和NativeAppEventEmitter,它们看起来完全相同.

他们之间有什么区别?我为什么要挑一个呢?

小智 9

双方DeviceEventEmitterNativeAppEventEmitter已被弃用,你应该使用NativeEventEmitter来代替。

  • 你是从哪里知道的?我在 RN 文档中的任何地方都没有看到这个 (2认同)

Ben*_*ton 4

我发现在开发需要将事件从 Java/Obj-C 发送到 JavaScript 的跨平台本机扩展时需要同时使用这两种扩展。

在 iOS 上,您可以像这样向 JS 发送事件:

[self.bridge.eventDispatcher sendAppEventWithName:@"myProgressEvent" body:@{               
 @"progress": @( (float)loaded / (float)total )
}];
Run Code Online (Sandbox Code Playgroud)

..你可以使用 JS 在 JS 中获取它NativeAppEventEmitter

在 Java 中,您可以通过以下方式将事件发送到 JS:

WritableMap map = Arguments.createMap();
map.putDouble("progress", progress);
getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
        .emit("myProgressEvent", map);                                                                                   
Run Code Online (Sandbox Code Playgroud)

..你在 JS 中使用DeviceEventEmitter

这并不理想,因为您的 JS 代码需要为要接收的事件选择正确的发射器。

例如

    const emitter = Platform.OS == 'ios' ? NativeAppEventEmitter : DeviceEventEmitter;
    emitter.addListener("myProgressEvent", (e:Event)=>{
        console.log("myProgressEvent " + JSON.stringify(e));
        if (!e) {
            return;
        }
        this.setState({progress: e.progress});
    });                                                                                             
Run Code Online (Sandbox Code Playgroud)

  • 这不是选择其中之一而不是另一个的理由,因为它是错误的。查看 iOS 的 RCTEventDispatcher 的 sendDeviceEventWithName 和 React Native Android 的 com.facebook.react.modules.core.RCTNativeAppEventEmitter,您可以从两个平台发送到两个事件发射器。 (3认同)