javascript - What is the method can I use to send an event from native module to JS in React Native - Stack Overflow

According to React Native documentation, you can use sendAppEventWithName to send an event from native

According to React Native documentation, you can use sendAppEventWithName to send an event from native code to JS. But in my XCode, code suggestions tell me that this method is deprecated.

This issue indicates that sendDeviceEventWithName should work but actually it's also deprecated.

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

According to React Native documentation, you can use sendAppEventWithName to send an event from native code to JS. But in my XCode, code suggestions tell me that this method is deprecated.

This issue indicates that sendDeviceEventWithName should work but actually it's also deprecated.

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

Share Improve this question asked Jul 12, 2016 at 10:19 JerryJerry 9277 silver badges25 bronze badges 1
  • It is deprecated because you should subclass the RCTEventEmitter as of now. Unfortunately I can't tell you how but you can take a look in the repository history of the event dispatcher here under change #21 – KRONWALLED Commented Jul 12, 2016 at 10:32
Add a ment  | 

1 Answer 1

Reset to default 7

UPDATE: Please take a look at this issue in which many people gave a lot of useful solutions.


I figured it out by reading its source code. Using the RCTEventEmitter class.

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

So you can send an event called sayHello with data Hello to JavaScript by calling the tellJS method.

In JavaScript side, you have to use the NativeModules module to get this native module and wrap it in NativeEventEmitter class so that you can receive events.

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744646821a4585660.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信