Rub*_*bys 18 react-native deviceeventemitter
我想使用事件在本机ios/android和我的本机应用程序之间进行通信.
我看到两种方法:DeviceEventEmitter和NativeAppEventEmitter,它们看起来完全相同.
他们之间有什么区别?我为什么要挑一个呢?
小智 9
双方DeviceEventEmitter并NativeAppEventEmitter已被弃用,你应该使用NativeEventEmitter来代替。
我发现在开发需要将事件从 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)
| 归档时间: |
|
| 查看次数: |
9758 次 |
| 最近记录: |