版权声明:本文为博主原创文章,未经博主容许不得转载。javascript
参考:http://blog.csdn.net/pz789as/article/details/52837853html
记得在0.27版本以前,RN的文档里面就告诉了咱们怎么从Native端主动发消息到JS端,上面说的方式是这样的:java
[objc] view plain copyreact
- @synthesize bridge = _bridge;
-
- -(void)iseCallback:(NSString*)code result:(NSString*) result
- {
- [_bridge.eventDispatcher
- sendDeviceEventWithName:@"iseCallback"
- body:@{
- @"code":code,
- @"result":result,
- @"index":self.bridgeIndex,
- @"category":self.bridgeCategory
- }];
- }
而后JS那边调用:ios
[javascript] view plain copygit
- import RCTDeviceEventEmitter from 'RCTDeviceEventEmitter';
-
- this.listener = myNativeEvt.addListener('iseCallback', this.iseCallback.bind(this));
-
- this.listener && this.listener.remove();
直接使用bridge.eventDispatcher中的方法,里面有三个,分别是:github
sendAppEventWithNamereact-native
sendDeviceEventWithNamexcode
sendInputEventWithNameapp
而后在JS那边也有三个对应的接收接口
RCTAppEventEmitter
RCTDeviceEventEmitter
RCTInputEventEmitter
虽然目前均可以使用,可是在xcode里面一直提示这种方式可能要被取代:
'sendDeviceEventWithName:body:' is deprecated: Subclass RCTEventEmitter instead
而后文档也没见到新方式的例子。
到目前为止,RN的 中文文档 和 英文原文文档 都没有看到,因而就去RN的github上找答案,结果上面有人已经提了。作法是这样的:
原生端修改:
一、自定义的模块类头文件要继承自RCTEventEmitter
[objc] view plain copy
- #import "RCTEventEmitter.h"
-
- @interface ChivoxISE : RCTEventEmitter<RCTBridgeModule>
二、而后要导出你全部的方法名字
[objc] view plain copy
- - (NSArray<NSString *> *)supportedEvents
- {
- return @[@"iseCallback", @"iseVolume", @"playCallback"];//有几个就写几个
- }
三、分别实现你导出的全部方法,里面都使用 sendEventWithName 方法便可
[objc] view plain copy
- -(void)iseCallback:(NSString*)code result:(NSString*) result
- {
- [self sendEventWithName:@"iseCallback"
- body:@{
- @"code": code,
- @"result": result,
- }];
- }
四、最后JS端调用
[javascript] view plain copy
- import {
- ...
- NativeModules,
- NativeEventEmitter, //导入NativeEventEmitter模块
- } from 'react-native';
-
- var ChivoxISE = NativeModules.ChivoxISE;
- const myNativeEvt = new NativeEventEmitter(ChivoxISE); //建立自定义事件接口
-
- //在组件中使用
- componentWillMount() {
- this.listener = myNativeEvt.addListener('iseCallback', this.iseCallback.bind(this)); //对应了原生端的名字
- }
- componentWillUnmount() {
- this.listener && this.listener.remove(); //记得remove哦
- this.listener = null;
- }
[javascript] view plain copy
- iseCallback(data) {//接受原生传过来的数据 data={code:,result:}
- if (data.code == CB_CODE_RESULT) {
- //
- }
- else {//..真的是未知的错误
- logf('传回其余参数', data.result);
- }
- }
五、结束。O(∩_∩)O哈哈~