react-native 调用原生模块详解

前端之家收集整理的这篇文章主要介绍了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"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       /* WritableMap params = Arguments.createMap();
        params.putString("TAG",tag);
        params.putString("MSG",message);
        getReactApplicationContext()
                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit("logInConsole",params);//对应的javascript层的事件名为logInConsole,注册该事件即可进行回调*/
    }

    public Map<StringgetConstants() {
        final Map<StringnewHashMap()        constants.put(TAG_KEYTAG_VALUE)        return constants    }
}
二,继承ReactPackage,实现如下

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


    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        List<NativeModule> modules=new ArrayList<NativeModule>()        ReactLogModule reactLogModule=new ReactLogModule(reactContext)        modules.add(reactLogModule)        return modulespublic List<Class<? extends JavaScriptModule>> createJSModules() {
        return Collections.emptyList()public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        添加package
mReactInstanceManager = ReactInstanceManager.builder()
        .setApplication(((Activity) mContext).getApplication())

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

        .setUseDeveloperSupport(false)
        .setInitialLifecycleState(LifecycleState.RESUMED)
        .build();
mReactRootView.startReactApplication(mReactInstanceManager"OperationActivity";
原文链接:https://www.f2er.com/react/307057.html

猜你在找的React相关文章