我正在按照此处的指南在 React Native 中创建 Turbo 模块。 https://reactnative.dev/docs/next/the-new-architecture/pillars-turbomodules
如何在 iOS 上发出事件?该文档仅展示了如何从 React 调用 native 函数,但没有展示如何从 Turbo 模块发出事件。
对于 Android,您会得到一个 ReactApplicationContext
对象,它允许您使用上下文对象创建这样的发射器。
private val emitter = context.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
emitter.emit(eventName, eventArray)
如何在 iOS 上做同样的事情?
最佳答案
要从 iOS 向 RN 发送事件,您应该创建自己的从 RCTEventEmitter
继承的发射器类,然后在 JS 端使用 NativeEventEmitter
初始化它并添加所需的监听器使用 addListener
的事件:
EventEmitter.h
#import <React/RCTEventEmitter.h>
@interface EventEmitter : RCTEventEmitter
+ (instancetype)shared;
@end
EventEmitter.m
#import "EventEmitter.h"
// Events
static NSString* onMyEvent = @"onMyEvent";
// Variable to save the instance
static EventEmitter* eventEmitter = nil;
@implementation EventEmitter
/// Exposing "EventEmitter" name to RN
RCT_EXPORT_MODULE(EventEmitter);
// Called from RN
- (instancetype)init {
if (self = [super init]) {
eventEmitter = self;
}
return self;
}
+ (BOOL)requiresMainQueueSetup {
return NO;
}
+ (instancetype)shared {
return eventEmitter;
}
// List of supported events
- (NSArray<NSString *> *)supportedEvents {
return @[onMyEvent];
}
@end
调用方式:
NSDictionary* body = @{@"message" : @"Hello Emitter!"};
[EventEmitter.shared sendEventWithName:@"onMyEvent" body:body];
注册护士/JS
import {
...
NativeEventEmitter,
NativeModules,
} from 'react-native';
import type EmitterSubscription from 'react-native';
class EventHandler extends React.Component {
eventsSubscription: EmitterSubscription;
componentDidMount() {
const eventEmitter = new NativeEventEmitter(NativeModules.EventEmitter);
this.eventsSubscription = eventEmitter.addListener('onMyEvent', event => {
console.log(event.message); // Prints "Hello Emitter!"
});
}
componentWillUnmount() {
this.eventsSubscription.remove();
}
...
};
关于java - 如何在 iOS 上的 Turbo 模块中发出事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74147421/