ReactNative读取Native本地文件
2016-10-17 20:23
337 查看
1, LatticeMockModule.java 声明一个Native模块给RN提供调用
2, LatticeMockModule.java 提供读取配置的方法
3,FReactPackage.java中注册此RN功能
4, 在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;
相关文章推荐
- React Native 之读取JSON 文件
- SAP 读取本地文件
- Net/C# 应用程序直接读取本地 Cookies 文件
- JS读取本地excel文件
- js读取本地文件
- JAVASCRIPT 读取本地文件
- .Net/C# 应用程序直接读取本地 Cookies 文件 (由于 WinXP SP2 调用 API: InternetGetCookie 无果)
- C#读取sqlserver 动画flash swf 文件到本地硬盘
- jdom 或 dom4j读取xml文件时如何让dtd验证使用本地dtd文件或者不生效
- 读取本地 文件 和 URL网络 文件 的 两个例子
- js读取本地文件
- 读取本地文件
- MSSQL 读取本地文件数据
- MSSQL 读取本地文件数据
- jdom 或 dom4j读取xml文件时如何让dtd验证使用本地dtd文件或者不生效
- 从URL读取文件保存到本地
- J2ME读取本地文件的方法
- 读取文件的本地时间(不打开文件)
- 读取本地UTF-8文件带有换行的中文文本
- C# 本地txt文件读取至comboBox下拉列表