React 调用Native原生方法

流程

Native端
  1. 创建类A继承ReactContextBaseJavaModule,并自定义JS需要调用的方法,主要需要加上 @ReactMethod注解;
  2. 创建类B实现ReactPackage接口,并实现其createNativeModules方法;
  3. 在包含React的Activity页面上使用ReactInstanceManager.builder()添加刚才实现的ReactPackage
React端
  1. 创建A.js文件,导入NativeModules,并通过实现Android端A类的getName方法返回的字符串导出;
  2. 在需要调用的位置引入模块,执行调用。

Native代码

ToastModule.java

public class ToastModule extends ReactContextBaseJavaModule {

    private static final String DURATION_SHORT_KEY = "SHORT";
    private static final String DURATION_LONG_KEY = "LONG";

    public ToastModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return "ToastExample";
    }

    @Nullable
    @Override
    public Map getConstants() {
        final Map constants = new HashMap<>();
        constants.put(DURATION_SHORT_KEY, Toast.LENGTH_SHORT);
        constants.put(DURATION_LONG_KEY, Toast.LENGTH_LONG);
        return constants;
    }

    @ReactMethod
    public void show(String message, int duration) {
        Toast.makeText(getReactApplicationContext(), message, duration).show();
    }

    @ReactMethod
    public void getData(String text, Callback callback) {
        callback.invoke("test", text);
    }
}

ToastReactPackage.java

public class ToastReactPackage implements ReactPackage {
    @Override
    public List createNativeModules(ReactApplicationContext reactContext) {
        List modules = new ArrayList<>();
        modules.add(new ToastModule(reactContext));
        return modules;
    }

    @Override
    public List createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }
}

Activity.java

// MainReactPackage必须添加
mReactInstanceManager = ReactInstanceManager.builder()
                .setApplication(getApplication())
                .setBundleAssetName("index.android.bundle")
                .setJSMainModulePath("index")
                .addPackage(new MainReactPackage())
                .addPackage(new ToastReactPackage())
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();

React代码

ToastAn.js

import {NativeModules} from 'react-native';
module.exports = NativeModules.ToastExample;

UI.js

 _toast() {
    ToastExample.getData("显示吐司内容", (arg1, arg2) => {
      ToastExample.show(arg1 + arg2, ToastExample.SHORT);
    });
  }

你可能感兴趣的:(react-native)