原文: https://hubcarl.github.io/blog/2016/08/13/react-native-plugin/

编写自定义插件需要继承ReactContextBaseJavaModule和实现ReactPackage接口, 具体实现步骤如下:

1. 继承ReactContextBaseJavaModule接口

public class IntentModule extends ReactContextBaseJavaModule

2. 重写 getName方法,暴露给JS端调用名

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

3. 给暴露给JS的方法添加 @ReactMethod 注解,且方法的返回值只能是void

@ReactMethod
public void backActivity(int count) {
    if (count > 0) {
        try {
            Activity currentActivity = getCurrentActivity();
            currentActivity.finish();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

4.实现ReactPackage接口

public class IntentPackage implements ReactPackage {
    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        return Arrays.<NativeModule>asList(
                new IntentModule(reactContext)
        );
    }
    @Override
    public List<Class<? extends JavaScriptModule>> createJSModules() {
        return Collections.emptyList();
    }
    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }
}

5.在Application中注册IntentPackage

@Override
protected List<ReactPackage> getPackages() {
  return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
          new IntentPackage()
  );
}

6.JavaScript调用IntentModule的backActivity方法

NativeModules.IntentModule.backActivity();

Author: sky
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint polocy. If reproduced, please indicate source sky !
 Previous
React Native Android APK包大小分析 React Native Android APK包大小分析
原文:https://hubcarl.github.io/blog/2016/08/21/react-native-size/React Native SO库React Native 打包后文件大小分析React Native java jar包分类和主要作用React Native 详细引用j...
2020-04-18 sky
Next 
轻轻松松搞定 Webpack 项目构建 轻轻松松搞定 Webpack 项目构建
基于 easywebpack 工程体系,你能非常简单,快速的编写出 webpack 复杂的配置,你无需过多关心热更新,是否压缩,是否Hash,公共JS/CSS,DLL,构建速度等问题,这些 easywebpack 都已经帮你解决和优化了。easywebpack 提供 Vue/React/JS/...
2020-04-18 sky