原生模块、原生ui组件、原生交互传值

 1.定义Module类:
    public class CommunicationModule extends ReactContextBaseJavaModule {

        private static final String LONG_TIME = "LONG";
        private static final String SHORT_TIME = "SHORT";

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

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

        @Override
        public Map<String, Object> getConstants() {
            Map<String, Object> constants = new HashMap<>();
            constants.put(LONG_TIME, Toast.LENGTH_LONG);
            constants.put(SHORT_TIME, Toast.LENGTH_SHORT);
            return constants;
        }

        //代表改方法是给RN使用
        @ReactMethod
        public void show(int duration) {
            Toast.makeText(getReactApplicationContext(), "message:" + duration, duration).show();
        }

        /**xxxxxxxxxxxxxxxxxxx重点
        *
        * js给android传值:通过方法的参数传递即可
        *
        * android给js传值:callback回调函数即可
        */
        @ReactMethod
        public void testAndroidCallbackMethod(String msg, Callback callback) {
            //msg是js给android传递的参数
            Toast.makeText(getReactApplicationContext(), msg, Toast.LENGTH_LONG).show();
            //android给js传值使用:callback回调函数即可
            callback.invoke("lzj123134545");
        }

        @ReactMethod
        public void textAndroidPromiseMethod(String msg, Promise promise) {
            //msg是js给android传递的参数
            Toast.makeText(getReactApplicationContext(), msg, Toast.LENGTH_SHORT).show();
            //android给js传值使用:promise异步编程返回
            promise.resolve("android给js传值使用");
        }

        //获取Intent传值
        @ReactMethod
        public void getDataFromIntent(Callback callback) {
            try {
                Activity currentActivity = getCurrentActivity();
                String result = currentActivity.getIntent().getStringExtra("name");
                if (TextUtils.isEmpty(result)) {
                    callback.invoke("no_data");
                } else {
                    callback.invoke(result);
                }
            } catch (Exception e) {
                callback.invoke("error");
            }
        }
    }       

    2.定义Package类:
    public class CommunicationPackage implements ReactPackage {
        @Override
        public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
            List<NativeModule> list = new ArrayList<>();
            list.add(new CommunicationModule(reactContext));
            return list;
        }

        @Override
        public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
            List<ViewManager> list = new ArrayList<ViewManager>();
            return list;
        }
    }    


    3.将Package类写入到Application 中:
    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
              new CommunicationPackage()
      );
    }


    4.js使用:

    Communication.js
        //引用原生模块
        import { NativeModules } from "react-native";

        //使用原生模块
        export default NativeModules.CommunicationModule;

    CommunicationTest.js:测试使用类
        import Communication from "./Communication";

        export default class CommunicationTest extends Component {
            constructor(props) {
                super(props);

                this.state = {
                  data: "Welcome to React Native!"
                };
            }

            componentDidMount() {
                Communication.getDataFromIntent(result => {
                    this.setState({
                        data: result
                    });
                });
            }

            render() {
                return (
                <View style={styles.container}>
                    <Text
                    style={styles.welcome}
                    onPress={() => {
                        // Communication.show(100);


                        // Communication.testAndroidCallbackMethod("dasdasdasdas", result => {
                        //   Alert.alert(result);
                        // });


                        // Communication.textAndroidPromiseMethod("abcx")
                        //   .then(result => {
                        //     Alert.alert(result);
                        //   })
                        //   .catch(error => {
                        //     Alert.alert(error);
                        //   });

                    }}
                    >
                    {this.state.data}
                    </Text>
                </View>
                );
            }
        }        

猜你喜欢

转载自blog.csdn.net/qq_42832884/article/details/83244661