版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_23575795/article/details/81298142
对于原生端自定义模块,注册模块,和RN层调用可以参考上一篇文章React-native调用Android原生模块.
RN层和Native层通信有三种法式(CallBack,Promise,RCTDeviceEventEmitter),前两种是一对一关系由js一次调起native给出结果,RCTDeviceEventEmitter(事件)由native多次发起,会造成js多次接收,不推荐使用事件方式.
这里以Promise为例,完成通信,其它两种demo里由具体实现:
1.在自定义模块里暴露给JS调用的方法中接收JS传递的数据:
//native
@ReactMethod
public void pickImage(String msg, Promise promise) {
final Activity currentActivity = getCurrentActivity();
Log.d("from JS",msg);
this.promise=promise;
if (currentActivity == null) {
return;
}
if (currentActivity instanceof MainActivity){
((MainActivity) currentActivity).setSelect();
}
}
2.在原生端处理完业务后,向RN传递数据:
//2.在native层使用Promise
public void sendMsgToJS(String msg){
promise.resolve(msg);
}
3.在JS里调用和接收消息:
<Text style={styles.textInputTitle} onPress={()=>this.promiseNative("向native传递数据")}> </Text>
promiseNative(msg) {
ImagePickerModule.pickImage(msg).then(
(result) =>{
Alert.alert(result)
}
).catch((error) =>{console.log(error)});
}
具体实现可以参考demo:https://github.com/RightOfHand/FirstApp