• React Native 入门(三)——js与native互相通信


    使用AndroidStudio打开项目中的android目录:

    在这里插入图片描述
    并等待Gradle Build完成,首次Build会花费不少时间,耐心等待!

    编译成功后如图:

    在这里插入图片描述

    首先我们来介绍js调用native方法:

    1.新建文件夹mymoudles和myreactpackage;

    2.在mymoudles中新建类ToastMoudle;

    public class ToastModule extends ReactContextBaseJavaModule {
    
        private ReactApplicationContext mContext;
    
        public ToastModule(ReactApplicationContext reactContext) {
            super(reactContext);
            mContext = reactContext;
        }
    
        @Override
        public String getName() {
            return "Toast";
        }
    
        @ReactMethod
        public void show(String msg) {
            Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    3.在myreactpackage中新建类MyReactPackage;

    public class MyReactPackage implements ReactPackage {
    
        static ReactApplicationContext reactContext;
    
        @Override
        public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
            MyReactPackage.reactContext = reactContext;
            List<NativeModule> modules = new ArrayList<>();
            modules.add(new ToastModule(reactContext));
            return modules;
        }
    
        @Override
        public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
            return Collections.emptyList();
        }
    
        public static void sendEvent(String eventName, String params) {
            reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName, params);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    4.在MainApplication的getPackages方法中,添加MyReactPackage:

    在这里插入图片描述

    在React的PageOne中测试:

    	import {
    	    NativeModules,
    	    ...
    	} from 'react-native';
    	
        testNativeFunc() {
            NativeModules.Toast.show('调用NativeToast成功');
        }
    
        render() {
            return (
                <SafeAreaView>
                    <StatusBar barStyle='dark-content' backgroundColor='#fff' />
                    <View style={styles.container}>
                        <Text style={{ color: '#000', fontSize: 30, fontWeight: 'bold' }} onPress={() => this.toPageTwo()}>PageOne</Text>
                        <Text onPress={() => this.testNativeFunc()} style={{backgroundColor:"#eee",padding:10}}>调用NativeToast</Text>
                    </View>
                </SafeAreaView>
            );
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    注意: 每当Native中的代码改动后,要生效就必须重新安装应用:关掉nodejs服务,并重新执行 npx yarn android!

    在这里插入图片描述
    是不是非常简单?

    那本地如何调用js呢?这里就需要用到DeviceEventEmitter,在本地代码中发射事件,在js代码中接收事件:

     reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName, params);
    
    • 1
    let eventEmitter;
    
    componentDidMount = () => {
    	eventEmitter = DeviceEventEmitter.addListener('event', (params) => {
    	          
    	});
    }
    
    componentWillUnmount = () => {
        if (eventEmitter) eventEmitter.remove();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    我们来测试一下,在点击按钮弹出Toast的同时,让Native发射一个事件到js,js接收到参数并显示出来:

    ToastMoudle中加上发送代码:

        @ReactMethod
        public void show(String msg) {
            Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
            mContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("event", "native调js");
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    PageOne中加上接收代码:

    import {
        DeviceEventEmitter,
        ...
    } from 'react-native';
    
    let eventEmitter;
    
    export default class PageOne extends React.Component {
    
        constructor(props) {
            super(props);
            this.state = {
                text: ""
            };
        }
       ...
        componentDidMount = () => {
            eventEmitter = DeviceEventEmitter.addListener('event', (params) => {
                console.log("event>>" + params);
                this.setState({
                    text: params
                });
            });
        }
    
        componentWillUnmount = () => {
            if (eventEmitter) eventEmitter.remove();
        }
        
        render() {
            return (
                <SafeAreaView>
                    <StatusBar barStyle='dark-content' backgroundColor='#fff' />
                    <View style={styles.container}>
                        <Text style={{ color: '#000', fontSize: 30, fontWeight: 'bold' }} onPress={() => this.toPageTwo()}>PageOne</Text>
                        <Text onPress={() => this.testNativeFunc()} style={{ backgroundColor: "#eee", padding: 10 }}>调用NativeToast</Text>
                        <Text style={{ color: '#FF0000', fontSize: 20, marginTop: 20 }} >{this.state.text}</Text>
                    </View>
                </SafeAreaView>
            );
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    重新安装应用,点击按钮:

    在这里插入图片描述
    在这里插入图片描述

    调用成功!

  • 相关阅读:
    机器学习 | 降维:PCA主成分分析
    oracle数据库核心知识
    开启安全测试评估赛道,永信至诚发布“数字风洞”产品体系
    Nginx+rtmp+ffmpeg搭建视频转码服务
    UVA-1602 网格动物 题解答案代码 算法竞赛入门经典第二版
    Python 批量合并图片到word文档
    计算机图像处理:图像轮廓
    Java项目:SSM网上超市购物商城管理系统
    SpringBoot 自动装配原理
    【智能优化算法】基于沙猫群优化算法求解单目标优化问题附matlab代码
  • 原文地址:https://blog.csdn.net/baiyuliang2013/article/details/126747444