react-native

React Native DeviceEventEmitter/

2020-03-11  本文已影响0人  罗坤_23333

DeviceEventEmitter for android

JavaScript端

import { DeviceEventEmitter } from 'react-native';

// addListener
let context = null;
DeviceEventEmitter.addListener('YOUR_EVENTNAME', (msg) => {
   console.log(msg);
   console.log(this); // null
 },context);

// emit
DeviceEventEmitter.emit('YOUR_EVENTNAME',msg);

//removeAllListeners
DeviceEventEmitter.removeAllListeners('YOUR_EVENTNAME');

Android拓展实现

import com.facebook.react.modules.core.DeviceEventManagerModule;

getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
            .emit("YOUR_EVENTNAME", "msg");

最初DeviceEventEmitter是用于发送原生的BackPress点击事件,
所以Android通过DeviceEventEmitter.emit()Android RCTDeviceEventEmitter emit都可以触发执行。

NativeEventEmitter for iOS

JavaScript端

import { NativeModules,NativeEventEmitter } from 'react-native';
const { IOSNativeModule } = NativeModules;

this._eventEmitter = new NativeEventEmitter(IOSNativeModule);
this._eventEmitter.addListener("IOS_EVENTNAME",(msg) => {
   console.log(msg)
})

this._eventEmitter.removeAllListeners("IOS_EVENTNAME")

iOS拓展实现

.h文件需要修改为继承RCTEventEmitter

#import <React/RCTBridgeModule.h>
+ #import <React/RCTEventEmitter.h>

- @interface AwesomeModule : NSObject <RCTBridgeModule>
+ @interface AwesomeModule : RCTEventEmitter <RCTBridgeModule>

@end

.m文件

// 注册事件名称
- (NSArray<NSString *> *)supportedEvents
{
  return @[@"EventReminder"];
}

// 派送指定名称的事件
[self sendEventWithName:@"EventReminder" body:@{@"name": data}];

Issue

Reference

上一篇下一篇

猜你喜欢

热点阅读