RN开发-Android原生交互

  在使用RN开发过程中,难免有些原生功能需要要自己来实现,下面总结一下在使用RN与原生开发交互。

1、在原生代码中定义实现类

  1.1  首先继承 ReactContextBaseJaveModule抽象类

    public class SomeModule extends ReactContextBaseJavaModule{}

  1.2  实现构造方法

    public SomeModule(ReactApplicationContext context){

      super(context);

    }

  1.3  实现 getName() 方法,并返回一个字符串

    @Override

    public String getName(){

      return "SomeModule"; //返回值将在RN代码中使用

    }

  1.4  实现功能方法,使用注解@ReactMethod修饰(使用修饰ReactMethod的方法,可以在RN中被调用)

    @ReactMethod

    public void callbackMethod(Object paramsFromJS,Callback ok,Callback error){

      //... do something , result = true

      if(result){

        ok.invoke("params");

      }else{

        error.invoke("error");

      }

    }

    @ReactMethod

    public void promiseMethod(Object paramsFromJS,Promise promise){

      // ... do something, result = true

      if(result){

        promise.resolve("params");

      }else{

        promise.reject("error");

      }

    }

2、原生注册模块

  2.1 注册模块

  实现ReactPackage接口

  public class SomeReactPackage implements ReactPackage{

    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext){

      return Collections.<NativeModule>singletonList(new SomeModule(reactContext));

    }

    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {

      return Collections.emptyList();

    }

    public List<Class<? extends JavaScriptModule>> createJSModules() {

      return Collections.emptyList();

    }

  } 

  2.2  添加模块

    在MainPackage类的getPackages()方法中添加模块

    public List<ReactPackage> getPackages() {

      return Arrays.<ReactPackage>asList(new MainReactPackage(),new SomeReactPackage());

    }

3、RN中JS代码

  3.1  首先导入库

    import { NativeModules } from 'react-native'

  3.2  调用原生方法

    3.2.1回调方法

      NativeModules.SomeModule.callbackMethod('params',(ok)=>{},(error)=>{});

    3.2.2 Promise方法    

      NativeModules.SomeModule.promiseMethod('params').then((ok)=>{}).catch((error)=>{});

    3.2.3 说明

      NativeModules : 不用解释,react-native提供的类库

      SomeModule : 原生代码中,getName()方法返回字符串

      callbackMethod() / promiseMethod() : 原生代码中,使用@ReactMethod修饰的方法

      (ok)=>{} : 成功回调方法

      (error)=>{} : 失败回调方法

    

至此,RN与原生混合开发最基本的流程已经OK 。

 

posted @ 2016-12-08 16:49  农民子弟  阅读(5200)  评论(0编辑  收藏  举报