React-Native新版本RCTEventEmitter的使用(从原生发送消息到JS)

记得在0.27版本之前,RN的文档里面就告诉了我们怎么从Native端主动发消息到JS端,上面说的方式是这样的:

[objc] view plain copy

@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那边调用:

[javascript] view plain copy

import RCTDeviceEventEmitter from 'RCTDeviceEventEmitter';

this.listener = myNativeEvt.addListener('iseCallback', this.iseCallback.bind(this));

this.listener && this.listener.remove();

直接使用bridge.eventDispatcher中的方法,里面有三个,分别是:
sendAppEventWithName
sendDeviceEventWithName
sendInputEventWithName
然后在JS那边也有三个对应的接收接口
RCTAppEventEmitter
RCTDeviceEventEmitter
RCTInputEventEmitter
虽然目前都可以使用,但是在xcode里面一直提示这种方式可能要被取代:
'sendDeviceEventWithName:body:' is deprecated: Subclass RCTEventEmitter instead
然后文档也没见到新方式的例子。

到目前为止,RN的 中文文档 和 英文原文文档 都没有看到,于是就去RN的github上找答案,结果上面有人已经提了。做法是这样的:
原生端修改:
1、自定义的模块类头文件要继承自RCTEventEmitter

[objc] view plain copy

import "RCTEventEmitter.h"

@interface ChivoxISE : RCTEventEmitter

2、然后要导出你所有的方法名字
[objc] view plain copy

  • (NSArray *)supportedEvents
    {
    return @[@"iseCallback", @"iseVolume", @"playCallback"];//有几个就写几个
    }

3、分别实现你导出的所有方法,里面都使用 sendEventWithName 方法即可

[objc] view plain copy

-(void)iseCallback:(NSString)code result:(NSString) result
{
[self sendEventWithName:@"iseCallback"
body:@{
@"code": code,
@"result": result,
}];
}

4、最后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);
}
}

5、结束。

转载自,http://blog.csdn.net/pz789as/article/details/52837853,有需要可以去问博主哈。

你可能感兴趣的:(React-Native新版本RCTEventEmitter的使用(从原生发送消息到JS))