最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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))

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论