您的位置:首页 > Web前端 > React

ReactNative读取Native本地文件

2016-10-17 20:23 337 查看
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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: