ReactNative桥接原生库

原生桥接1(类库桥接)

Native层 - Java

  • 继承 ReactContextBaseJavaModule,代码中只展示了三种通信方式。

    public class CustomBridgeLibrary extends ReactContextBaseJavaModule {
    
    private ReactApplicationContext mContext;
    
    public CustomBridgeLibrary(ReactApplicationContext reactContext) {
        super(reactContext);
        this.mContext = reactContext;
    }
    
    /**
     * 指定RN调用时的名称
     * "CUSTOM_LIBRARY_NAME": 库的调用名称,在RN层调用时,需保持命名一致.
     */
    @Override
    public String getName() {
        return "CUSTOM_LIBRARY_NAME";
    }
    
    /**
     * 1.声明RN调用Native的方法
     * "@ReactMethod": 加上此注解,才能被RN层正确调用.
     */
    @ReactMethod
    public void callByReact(String msg){
        Log.i("Native", "callByReact: " + msg);
    }
    
    /**
     * 2.Emitter-Native回传数据到RN
     * "EMIT_EVENT_NAME": Emitter的事件名称,在RN层监听时,事件名称需保持命名一致.
     * ".emit(eventName, data)": data: 发送到RN层的数据,
     *   对于复杂data数据,可以由 WritableNativeMap 或者 WritableNativeArray 封装.
     */
    public void sendMsgFromNative(String msg){
        mContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit("EMIT_EVENT_NAME", msg);
    }
    
    /**
     * 3.拓展: Promise形式调用Native的方法
     * "resolve": 正确处理时的返回值,data可以封装复杂数据.
     * "reject": 错误处理时的返回值.
     */
    public void callByReactPromise(String param, Promise promise) {
        //TODO do something
        if (true) {
            promise.resolve("data");
        } else {
            promise.reject("code", "error");
        }
    }
    }
  • 实现 ReactPackage

    public class CustomReactPackage implements ReactPackage {
    
    /**
     * 1.在这里加入供RN层调用的类库
     */
    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        ArrayList<NativeModule> modules = new ArrayList<>();
        modules.add(new CustomBridgeLibrary(reactContext));
        return modules;
    }
    
    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }
    }
  • 实现 ReactApplication

    public class MainApplication extends Application implements ReactApplication {
    
    private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
        @Override
        protected String getJSMainModuleName() {
            return "index";
        }
    
        @Override
        public boolean getUseDeveloperSupport() {
            return BuildConfig.DEBUG;
        }
    
        /**
         * 1.加入已声明的ReactPackage
         * "MainReactPackage()": 默认添加.
         */
        @Override
        protected List<ReactPackage> getPackages() {
            return Arrays.<ReactPackage>asList(
                    new MainReactPackage(),
                    new CustomReactPackage()
            );
        }
    };
    
    @Override
    public ReactNativeHost getReactNativeHost() {
        return mReactNativeHost;
    }
    
    @Override
    public void onCreate() {
        super.onCreate();
        SoLoader.init(this, /* native exopackage */ false);
    }
    }

RN层 - TypeScript

  • 在RN层调用原生库,代码中只展示了三种通信方式。

    export default class CustomRnCall extends Component {
    
    /**
     * NativeModules 和 DeviceEventEmitter 的包导入都来自'react-native'.
     * import {NativeModules, DeviceEventEmitter} from 'react-native'
     */
    NativeModuleBridge = NativeModules.CUSTOM_LIBRARY_NAME;
    
    /**
     * 1.主动调用原生库的方法
     */
    private callNativeMethod(msg: string){
        this.NativeModuleBridge.callByReact(msg)
    }
    
    constructor(props:any){
        super(props)
        /**
         * 2.Emitter监听来自Native的消息
         */
        DeviceEventEmitter.addListener('EMIT_EVENT_NAME',
            (msg: string) => {
                console.log("msg from native", msg)
            });
    }
    
    /**
     * 3.扩展: Promise形式调用原生库的方法
     */
    private callNativeByPromise(param: string) {
        this.NativeModuleBridge.callByReactPromise(param)
            .then((result: any) => {
                console.log("receive resolve")
            })
            .catch((error: any) => {
                console.log("receive reject")
            })
    }
    
    render (){
        return ({
            //TODO Add View Here
        })
    }
    }

猜你喜欢

转载自blog.csdn.net/pang_gua/article/details/80058712
今日推荐