Which method can I use to send events from native module to JS in React Native

According to the React Native documentation, you can use sendAppEventWithNameto send events from native code to JS. But in my Xcode, the code suggestions tell me that this method is deprecated.

enter image description here

This issue indicates that it sendDeviceEventWithNameshould work, but in fact it is also deprecated.

What is the actual way to send an event to JS?

+4
source share
1 answer

UPDATE . Please see this question in which many people have provided many useful solutions.


, . RCTEventEmitter.

MyModule.h

#import "RCTEventEmitter.h"
#import "RCTBridgeModule.h"

@interface MyModule : RCTEventEmitter <RCTBridgeModule>

@end

MyModule.m

@implementation MyModule

RCT_EXPORT_MODULE();

- (void)tellJS {
  [self sendEventWithName:@"sayHello" body:@"Hello"];
}

@end

, sayHello Hello JavaScript, tellJS.

JavaScript NativeModules, NativeEventEmitter, .

import { NativeModules, NativeEventEmitter } from 'react-native'

const myModuleEvt = new NativeEventEmitter(NativeModules.MyModule)
myModuleEvt.addListener('sayHello', (data) => console.log(data))
+6

All Articles