一个把终身献给代码的单身狗,寻找自由之路
刚写完iOS调用RN端代码的,现在写Android调用RN端代码的,只有一种方法
1、建立继承与MJToRNBridgeModulesTest类
package com.gomejr.icash.business.rn.MJRNComponment;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import javax.annotation.Nullable;
public class MJToRNBridgeModulesTest extends Object {
private final ReactContext reactContext;
public MJToRNBridgeModulesTest(ReactContext reactContext) {
super();
this.reactContext = reactContext;
}
public void refreshFinancialLifePage(String eventName, @Nullable WritableMap params) {
if (this.reactContext == null) {
return;
}
this.reactContext.getJSModule((DeviceEventManagerModule.RCTDeviceEventEmitter.class)).emit(eventName, params);
}
}
2、在需要调用的地方,实例化MJToRNBridgeModulesTest类,并把reactContext传给MJToRNBridgeModulesTest的实例
WritableMap params = Arguments.createMap();
MJToRNBridgeModulesTest module = new MJToRNBridgeModulesTest(getReactContext());
module.refreshFinancialLifePage(eventName, params);
获取reactContext的方法如下,首先获取到mReactInstanceManager
private ReactContext reactContext;
private ReactInstanceManager mReactInstanceManager;
private ReactContext getReactContext() {
return reactContext != null ? reactContext : mReactInstanceManager != null ? mReactInstanceManager.getCurrentReactContext() : null;
}
3、对应的RN代码如下
建立EventManager.js文件
import React, {
DeviceEventEmitter
}from 'react-native';
export default class EventManager{
subscription = null; //监听者
/**
* @param eventType 监听的名称,用来区分监听,String类型
* @param callback 监听的回调,需要监听的方法
*/
init = (eventType,callback) =>{
subscription = DeviceEventEmitter.addListener(eventType,() => {
callback();
});
}
/**
* 销毁监听
*/
destroy=()=>{
if (this.subscription != null) {
subscription.remove();
}
}
}
在需要的组件内
componentDidMount() {
this.eventManager = new EventManager();//创建
this.eventManager.init(‘'eventName', this._onHeaderRefresh);//注册事件
}
网友评论