react-native 调用原生模块详解


一,继承 ReactContextBaseJavaModule 实现如下方法  自定义方法用 @ReactMethod注释
/**
            * 日志打印module
    * Created by ybj on 2016/2/26.
            */
    public class ReactLogModule extends ReactContextBaseJavaModule {
        private static final String MODULE_NAME="Log";
    private static final String TAG_KEY = "TAG";
    private static final String TAG_VALUE = "LogModule";

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

    @Override
    public String getName() {
        return MODULE_NAME;
    }
    @ReactMethod
    public  void  d(String tag,String message){
        Log.d(tag,message);
       /* WritableMap params = Arguments.createMap();
        params.putString("TAG",tag);
        params.putString("MSG",message);
        getReactApplicationContext()
                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit("logInConsole", params);//对应的javascript层的事件名为logInConsole,注册该事件即可进行回调*/
    }

    @Override
    public Map, Object> getConstants() {
        final Map,Object> constants= MapBuilder.newHashMap();
        constants.put(TAG_KEY,TAG_VALUE);
        return constants;
    }
}
二,继承ReactPackage,实现如下

/**
 * 日志打印 需要打印日志注册this
 * Created by ybj on 2016/2/26.
 */
public class ReactLogPackage implements ReactPackage {


    @Override
    public List createNativeModules(ReactApplicationContext reactContext) {
        List modules=new ArrayList();
        ReactLogModule reactLogModule=new ReactLogModule(reactContext);
        modules.add(reactLogModule);
        return modules;
    }

    @Override
    public Listextends JavaScriptModule>> createJSModules() {
        return Collections.emptyList();
    }

    @Override
    public List createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }
}
三 添加package
 
  
mReactInstanceManager = ReactInstanceManager.builder()
        .setApplication(((Activity) mContext).getApplication())

        .setJSBundleFile(bundleFile)
                //  .setJSMainModuleName("test")
        .setNativeModuleCallExceptionHandler(new NativeModuleCallExceptionHandler() {
            @Override
            public void handleException(Exception e) {
            }
        })
        .addPackage(new MainReactPackage())
        .addPackage(new ReactLogPackage())
       

        .setUseDeveloperSupport(false)
        .setInitialLifecycleState(LifecycleState.RESUMED)
        .build();
mReactRootView.startReactApplication(mReactInstanceManager, "OperationActivity", null);

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