Calling a Android Native UI component method from React native Js code

前端 未结 3 1868
春和景丽
春和景丽 2021-02-08 09:06

I have created a CustomView SignatureView.java which extends LinearLayout for capturing signature in Android Native.

And created SignatureCapturePackage.java and Signatu

3条回答
  •  梦毁少年i
    2021-02-08 09:44

    I needed a solution that let me return values from my component instance method (Promises in my case). Using receiveCommand didn't allow me to do this.

    I was able to solve this using UIManagerModule.addUIBlock, similar to https://stackoverflow.com/a/31936516/194065:

    public class MyViewModule extends ReactContextBaseJavaModule {
    
        public static final String TAG = MyViewModule.class.getSimpleName();
    
        public MyViewModule(ReactApplicationContext reactContext) {
            super(reactContext);
        }
    
        @Override
        public String getName() {
            return "MyView";
        }
    
        @ReactMethod
        public void someMethod(final int viewId, final Promise promise) {
            withMyView(viewId, promise, new MyViewHandler() {
                @Override
                public void handle(MyView view) {
                    String value = view.someMethod();
                    promise.resolve(value)
                }
            });
        }
    
        private void withMyView(final int viewId, final Promise promise, final MyViewHandler handler) {
            UIManagerModule uiManager = getReactApplicationContext().getNativeModule(UIManagerModule.class);
            uiManager.addUIBlock(new UIBlock() {
                @Override
                public void execute(NativeViewHierarchyManager nativeViewHierarchyManager) {
                    View view = nativeViewHierarchyManager.resolveView(viewId);
                    if (view instanceof MyView) {
                        MyView myView = (MyView) view;
                        handler.handle(myView);
                    }
                    else {
                        Log.e(TAG, "Expected view to be instance of MyView, but found: " + view);
                        promise.reject("my_view", "Unexpected view type");
                    }
                }
            });
        }
    
    
    }
    

    Usage:

    import React, { Component } from 'react';
    import { NativeModules, requireNativeComponent, findNodeHandle } from "react-native";
    const MyViewFunctions = NativeModules.MyView;
    
    
    class MyView extends Component {
    
        someMethod() {
            MyViewFunctions.someMethod(findNodeHandle(this.nativeCmp));
        }
    
        render() {
            return (
                 this.nativeCmp = cmp}
                    {...this.props}
                />
            );
    }
    
    const RCMyView = requireNativeComponent('RCMyView', MyView);
    
    export default MyView;
    

提交回复
热议问题