react-native 调用原生模块详解

前端之家收集整理的这篇文章主要介绍了react-native 调用原生模块详解前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

  1. 一,继承 ReactContextBaseJavaModule 实现如下方法 自定义方法 @ReactMethod注释
  2. /**
  3. * 日志打印module
  4. * Created by ybj on 2016/2/26.
  5. */
  6. public class ReactLogModule extends ReactContextBaseJavaModule {
  7. private static final String MODULE_NAME="Log";
  8. private static final String TAG_KEY = "TAG"TAG_VALUE = "LogModule"
  9. public ReactLogModule(ReactApplicationContext reactContext) {
  10. super(reactContext) }
  11.  
  12. @Override
  13. public String getName() {
  14. return MODULE_NAME }
  15. @ReactMethod
  16. public void d(String tag,String message){
  17. Log.d(tag /* WritableMap params = Arguments.createMap();
  18. params.putString("TAG",tag);
  19. params.putString("MSG",message);
  20. getReactApplicationContext()
  21. .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
  22. .emit("logInConsole",params);//对应的javascript层的事件名为logInConsole,注册该事件即可进行回调*/
  23. }
  24.  
  25. public Map<StringgetConstants() {
  26. final Map<StringnewHashMap() constants.put(TAG_KEYTAG_VALUE) return constants }
  27. }
  1. 二,继承ReactPackage实现如下
  1. * 日志打印 需要打印日志注册this
  2. * Created by ybj on 2016/2/26.
  3. */
  4. public class ReactLogPackage implements ReactPackage {
  5.  
  6.  
  7. public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
  8. List<NativeModule> modules=new ArrayList<NativeModule>() ReactLogModule reactLogModule=new ReactLogModule(reactContext) modules.add(reactLogModule) return modulespublic List<Class<? extends JavaScriptModule>> createJSModules() {
  9. return Collections.emptyList()public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
  10. 添加package
  1. mReactInstanceManager = ReactInstanceManager.builder()
  2.         .setApplication(((Activity) mContext).getApplication())
  3.         .setJSBundleFile(bundleFile)
  4.                 //  .setJSMainModuleName("test")
  5.         .setNativeModuleCallExceptionHandler(new NativeModuleCallExceptionHandler() {
  6.                         public void handleException(Exception e) {
  7.             }
  8.         })
  9.         .addPackage(new MainReactPackage())
  10.         .addPackage(new ReactLogPackage())
  11.        
  12.         .setUseDeveloperSupport(false)
  13.         .setInitialLifecycleState(LifecycleState.RESUMED)
  14.         .build();
  15. mReactRootView.startReactApplication(mReactInstanceManager"OperationActivity";

猜你在找的React相关文章