【问题标题】:Sending events to JS React Native向 JS React Native 发送事件
【发布时间】:2019-05-02 12:28:59
【问题描述】:

我在 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

请帮忙。

谢谢, 克劳迪乌

【问题讨论】:

  • 能否添加条件 if(NativeModules) { const { ModuleWithEmitter } = NativeModules;常量 eventEmitter = new NativeEventEmitter(ModuleWithEmitter); }
  • 它不起作用,同样的错误。
  • 使用 RCTBridgeModule.h * 从 react native 调用 NativeModules.ModuleName.doSomethingAsync(aString) 并通过此 RCT_EXPORT_METHOD 中的相同方法名称接收(方法名称:参数)

标签: objective-c react-native


【解决方案1】:

该错误意味着您尚未链接您的模块。模块基本上是库,因此您必须将它们链接到主项目。检查这个:

https://facebook.github.io/react-native/docs/linking-libraries-ios

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多