objective-c - 向 JS React Native 发送事件
问题描述
我在Objective C事件发射器上实现了React Native,在那里我创建了一个发射器类,它发送事件以响应本机并且似乎可以工作:
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>
@interface PlayerEventsEmitter : RCTEventEmitter <RCTBridgeModule>
@end
#import "PlayerEventsEmitter.h"
@implementation PlayerEventsEmitter
{
bool hasListeners;
}
RCT_EXPORT_MODULE();
+ (id)allocWithZone:(NSZone *)zone {
static PlayerEventsEmitter *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [super allocWithZone:zone];
});
return sharedInstance;
}
- (NSArray<NSString *> *)supportedEvents {
return @[@"onMediaLoaded", @"onPlaying", @"onPause", @"onError", @"onEnded", @"onBuffering", @"onTimeUpdate", @"onStateUpdate"];
}
- (void)startObserving {
hasListeners = YES;
}
- (void)stopObserving {
hasListeners = NO;
}
- (void)sendEventName:(NSString *)eventName body:(id)body {
if (hasListeners) {
[self sendEventWithName:eventName body:body];
}
}
@end
但是当我这样做时在 JS 上:
import {NativeEventEmitter, NativeModules} from 'react-native';
import isFunction from 'lodash/isFunction';
import noop from 'lodash/noop';
import createMiddleware from './middleware';
const nativeAdapter = NativeModules.RNNativePlayerAdapter; // eslint-disable-line
const { ModuleWithEmitter } = NativeModules;
const eventEmitter = new NativeEventEmitter(ModuleWithEmitter);
const onMediaLoaded = (event) => {
console.log(event);
}
const onPlaying = (event) => {
console.log(event);
}
const subscription1 = eventEmitter.addListener('onMediaLoaded', onMediaLoaded);
const subscription2 = eventEmitter.addListener('onPlaying', onPlaying);
export default class NativeAdapter {
constructor() {
console.log('nativeAdapter: ', nativeAdapter);
console.log('NativeModules: ', NativeModules);
this.subscription = eventEmitter.addListener(
'onMediaLoaded',
(onMediaLoaded) => {
console.log('onMediaLoaded');
}
);
}
}
我收到一个错误:“本机模块不能为空”
我完全按照文档: https ://facebook.github.io/react-native/docs/native-modules-ios
请帮忙。
谢谢,克劳迪乌
解决方案
该错误意味着您尚未链接您的模块。模块基本上是库,因此您必须将它们链接到主项目。检查这个:
https://facebook.github.io/react-native/docs/linking-libraries-ios
推荐阅读
- reactjs - 使用 react-share 包时,“语法错误:导入声明只能出现在模块的顶层”
- javascript - 如何修复 Node.js/Express 中的竞争条件。我的控制台将正确更新但我的网页没有更新
- c - c 相当于 ucomisd
- javascript - 从列表数组中附加一个值 - 反应原生
- javascript - Vue.js 从父组件中更新子组件数据
- android - 在 Amlogic Android Media Boxes 的 webview 中自动播放视频
- javascript - 使用 Youtube API 调用的 iframe 在 Vue.js V-if 命令之后不会出现
- powerbi - 在 TIMEVALUE 数据上设置自定义开始/结束 x 轴
- javascript - 将数据传递给vuejs中的全局组件
- azure-cosmosdb - 如何在 Azure Cosmos DB 的一个查询中选择多个聚合值