1, LatticeMockModule.java 声明一个Native模块给RN提供调用
/**此类为RN提供读取配置文件的功能*/
public class LatticeMockModule extends ReactContextBaseJavaModule {
....
private final static String REACT_CLASS = "LatticeMockModule";
/**重写父类的方法*/
public LatticeMockModule(ReactApplicationContext reactContext) {
super(reactContext);
}
/**重写父类的方法*/
@Override
public String getName() {
return REACT_CLASS;
}
....
}
2, LatticeMockModule.java 提供读取配置的方法
...
private Map<String, String> configCache = new HashMap<>();
private final static String ASSET_PATH = "latticeConfig/";
...
/** 提供给RN调用读取配置的方法
*pageName= 页面名*/
@ReactMethod
public void getConfig(String pageName, Promise promise) {
String config = configCache.get(pageName);
Context context = getReactApplicationContext();
if (TextUtils.isEmpty(config)) {
config = ReadFromAsset(context, pageName);
}
//返回给RN处
promise.resolve(ReactArguments.toWritableMap(config));
configCache.put(pageName, config);
}
/**读取assts下的* latticeConfig/LatticeMockModule.json文件
private String ReadFromAsset(Context context, String pageName) {
try {
InputStream in = context.getAssets().open(ASSET_PATH + pageName + ".json");
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
StringBuffer sb = new StringBuffer();
String line;
while ((line = bf.readLine()) != null) {
sb.append(line);
}
line = sb.toString();
return line;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
3,FReactPackage.java中注册此RN功能
public class FReactPackage extends MainReactPackage {
....
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactApplicationContext) {
List<NativeModule> nativeModuleList = super.createNativeModules(reactApplicationContext);
List<NativeModule> list = new ArrayList<>();
list.addAll(nativeModuleList);
list.add(new LatticeMockModule(reactApplicationContext));
return list;
}
...
}
4, 在RN页面中调用
import React, {Component,} from 'react';
const NativeModules = require('NativeModules');
const LatticeMockModule = NativeModules.LatticeMockModule;
class LatticeHomeScreen extends Component {
//组件生命周期方法
componentDidMount() {
LatticeMockModule.getConfig("LatticeHomeScreen").then((config)=> {
alert(JSON.parse(config));//读取成功
});
}
}
module.exports = LatticeHomeScreen;