React native和原生之间的通信
RN中文网关于原生模块(Android)的介绍可以看到,RN前端与原生模块之
间通信,主要有三种方法:
1)使用回调函数Callback,它提供了一个函数来把返回值传回给JavaScript。
2)使用Promise来实现。
3)原生模块向JavaScript发送事件。
关于使用回调,这是最简单的一种通信,这里可以看看官网的实现,今天要讲的是滴三种由原生模块向JavaScript发送事件。
(1)首先,你需要定义一个发送事件的方法。如下所示:
- /*原生模块可以在没有被调用的情况下往JavaScript发送事件通知。
- 最简单的办法就是通过RCTDeviceEventEmitter,
- 这可以通过ReactContext来获得对应的引用,像这样:*/
- public static void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap paramss)
- {
- System.out.println("reactContext="+reactContext);
- reactContext
- .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
- .emit(eventName, paramss);
- }
其中方法名可以任意,但是参数不可改变。该方法可以放在你要复用的原生类中(即为原生类1)。
需要注意的是,由于版本问题,该函数中的参数reactContext有可能为null,此时会报NullPointException的错误。所以我们需要手动给reactContext赋值,见步骤2.
(2)我们在原生类1中,定义变量public static ReactContext MyContext;
然后在我们自定义的继承至ReactContextBaseJavaModule的类中给reactContext赋值。
如下所示:
- public class MyModule extends ReactContextBaseJavaModule {
- private BluetoothAdapter mBluetoothAdapter = null;
- public MyModule(ReactApplicationContext reactContext) {
- super(reactContext);
- 原生类1.MyContext=reactContext;
- }
- .......以下写被@ReactNative所标注的方法
- ............................
- ...................
- }
此时,reactContext将不会是null。也就不会报错。
(3)在某个原生函数中向JavaScript发送事件。如下所示:
- WritableMap event = Arguments.createMap();
- sendEvent(MyContext, "EventName",event);
(4)在RN前端监听事件。首先导入DeviceEventEmitter,即import{ DeviceEventEmitter } from 'react-native'
然后使用componentWillMount建立监听。
代码如下:
- componentWillMount(){
- DeviceEventEmitter.addListener('EventName', function() {
- alert("send success");
- });
- }
注意:该监听必须放在class里边,和render、const对齐。
);
前端index.android.js代码如下:
- /**
- * Sample React Native App
- * https://github.com/facebook/react-native
- * @flow
- */
- import React, { Component } from 'react';
- import {
- AppRegistry,
- StyleSheet,
- Text,
- DeviceEventEmitter,
- NativeModules,
- View
- } from 'react-native';
- export default class ywq extends Component {
- componentWillMount(){
- //监听事件名为EventName的事件
- DeviceEventEmitter.addListener('EventName', function() {
- alert("send success");
- });
- }
- constructor(props) {
- super(props);
- this.state = {
- content: '这个是预定的接受信息',
- }
- }
- render() {
- return (
- <View style={styles.container}>
- <Text style={styles.welcome}
- onPress={this.callNative.bind(this)}
- >
- 当你点我的时候会调用原生方法,原生方法延迟3s后会向前端发送事件。
- 前端一直在监听该事件,如果收到,则给出alert提示!
- </Text>
- <Text style={styles.welcome} >
- {this.state.content}
- </Text>
- </View>
- );
- }
- callNative()
- {
- NativeModules.MyModule.NativeMethod();
- }
- }
- const styles = StyleSheet.create({
- container: {
- flex: 1,
- justifyContent: 'center',
- alignItems: 'center',
- backgroundColor: '#F5FCFF',
- },
- welcome: {
- fontSize: 20,
- textAlign: 'center',
- margin: 10,
- },
- instructions: {
- textAlign: 'center',
- color: '#333333',
- marginBottom: 5,
- },
- });
- AppRegistry.registerComponent('ywq', () => ywq);
运行结果如下所示:
点击之前:
调用原生方法并且等待3s后:
再说一个值得注意的地方,一般我们在接收到原生模块主动发来的事件时,都会进行一些操作,如更新UI,而不仅仅是弹出alert 。
例如我们需要更新UI,代码如下:
- /**
- * Sample React Native App
- * https://github.com/facebook/react-native
- * @flow
- */
- import React, { Component } from 'react';
- import {
- AppRegistry,
- StyleSheet,
- Text,
- DeviceEventEmitter,
- NativeModules,
- View
- } from 'react-native';
- export default class ywq extends Component {
- componentWillMount(){
- //监听事件名为EventName的事件
- DeviceEventEmitter.addListener('EventName', function() {
- this.showState();
- alert("send success");
- });
- }
- constructor(props) {
- super(props);
- this.state = {
- content: '这个是预定的接受信息',
- }
- }
- render() {
- return (
- <View style={styles.container}>
- <Text style={styles.welcome}
- onPress={this.callNative.bind(this)}
- >
- 当你点我的时候会调用原生方法,原生方法延迟3s后会向前端发送事件。
- 前端一直在监听该事件,如果收到,则给出alert提示!
- </Text>
- <Text style={styles.welcome} >
- {this.state.content}
- </Text>
- </View>
- );
- }
- callNative()
- {
- NativeModules.MyModule.NativeMethod();
- }
- showState()
- {
- this.setState({content:'已经收到了原生模块发送来的事件'})
- }
- }
- const styles = StyleSheet.create({
- container: {
- flex: 1,
- justifyContent: 'center',
- alignItems: 'center',
- backgroundColor: '#F5FCFF',
- },
- welcome: {
- fontSize: 20,
- textAlign: 'center',
- margin: 10,
- },
- instructions: {
- textAlign: 'center',
- color: '#333333',
- marginBottom: 5,
- },
- });
- AppRegistry.registerComponent('ywq', () => ywq);
很明显:当收到事件时,改变一个文本框的内容,即更新UI。
运行结果如下,说明在此function中不能使用this,也就是我们并不能更新UI。
那我们能做到在接收到事件后更新UI等后续操作吗?
使用胖箭头函数(Fat arrow functions)
修改UI代码如下:
- /**
- * Sample React Native App
- * https://github.com/facebook/react-native
- * @flow
- */
- import React, { Component } from 'react';
- import {
- AppRegistry,
- StyleSheet,
- Text,
- DeviceEventEmitter,
- NativeModules,
- View
- } from 'react-native';
- export default class ywq extends Component {
- componentWillMount(){
- //监听事件名为EventName的事件
- DeviceEventEmitter.addListener('EventName', ()=> {
- this.showState();
- alert("send success");
- });
- }
- constructor(props) {
- super(props);
- this.state = {
- content: '这个是预定的接受信息',
- }
- }
- render() {
- return (
- <View style={styles.container}>
- <Text style={styles.welcome}
- onPress={this.callNative.bind(this)}
- >
- 当你点我的时候会调用原生方法,原生方法延迟3s后会向前端发送事件。
- 前端一直在监听该事件,如果收到,则给出alert提示!
- </Text>
- <Text style={styles.welcome} >
- {this.state.content}
- </Text>
- </View>
- );
- }
- callNative()
- {
- NativeModules.MyModule.NativeMethod();
- }
- showState()
- {
- this.setState({content:'已经收到了原生模块发送来的事件'})
- }
- }
- const styles = StyleSheet.create({
- container: {
- flex: 1,
- justifyContent: 'center',
- alignItems: 'center',
- backgroundColor: '#F5FCFF',
- },
- welcome: {
- fontSize: 20,
- textAlign: 'center',
- margin: 10,
- },
- instructions: {
- textAlign: 'center',
- color: '#333333',
- marginBottom: 5,
- },
- });
- AppRegistry.registerComponent('ywq', () => ywq);
运行之后,界面刷新了。
React native和原生之间的通信的更多相关文章
- React Native Android原生模块开发实战|教程|心得|怎样创建React Native Android原生模块
尊重版权,未经授权不得转载 本文出自:贾鹏辉的技术博客(http://blog.csdn.net/fengyuzhengfan/article/details/54691503) 告诉大家一个好消息. ...
- React Native 导入原生Xcode项目总结与记录
html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,bi ...
- React Native移植原生Android
(一)前言 之前已经写过了有关React Native移植原生Android项目的文章,不过因为RN版本更新的原因吧,跟着以前的文章可能会出现一些问题,对于初学者来讲还是会有很多疑难的困惑的,而且官方 ...
- React Native之原生模块的开发(Android)学习笔记
目录 1.为什么我们需要原生模块开发 2.开发Android原生模块的主要流程 3.原生模块开发实战 1.为什么我们需要原生模块开发? 我们在用RN开发App的时候,有时候需要用到一些原生模块 ...
- [转]Shared——React Native与原生关系理解与对比
零.关系理解 这个是我对RN和原生关系的理解.简单解释下这个图. RN js编写完业务代码后,通过react-native bundle命令,将代码分别编译成一个index.ios.bundle和in ...
- React Native与原生项目连接与发布
前面的各种环境配置按照官方文档一步一步来,挺详细,宝宝在这里就不多说废话了. 其次,前面的配置,我参照的这个博主的文章React Native 集成到iOS原生项目 下面是宝宝掉过的坑(半径15M): ...
- 【React Native开发】React Native移植原生Android项目(4)
),React Native技术交流4群(458982758),请不要反复加群!欢迎各位大牛,React Native技术爱好者加入交流!同一时候博客左側欢迎微信扫描关注订阅号,移动技术干货,精彩文章 ...
- react native与原生的交互
一.交互依赖的重要组件 react native 中如果想要调用ios 中相关的方法,必须依赖一个重要的组件nativemodules import { NativeModules } from ' ...
- React native中的组建通知通信:
有这么一个需求,在B页面pop()回到A页面,需要A页面执行刷新,那么我们可以采用以下方法: 1:在A页面Push到B页面中,加上一个A页面中的刷新函数做为参数,然后在B页面中在pop()函数封装后通 ...
随机推荐
- snmp爆破(python脚本)
snmp用来获取信息,然后利用获取的信息来进一步的渗透. 命令行有 snmpwalk -v 2c -c public ip system -c是密码,默认的密码是public 利用工具可以找windo ...
- 各种电脑进入BIOS快捷键
组装机主板 品牌笔记本 品牌台式机 主板品牌 启动按键 笔记本品牌 启动按键 台式机品牌 启动按键 华硕主板 F8 联想笔记本 F12 联想台式机 F12 技嘉主板 F12 宏基笔记本 F12 惠普台 ...
- Python 装饰器示例
#!/usr/bin/env python # _*_ coding: UTF-8 _*_ # Author:taoke def applePrice(func): def otherfunc(): ...
- Tensorflow学习笔记(对MNIST经典例程的)的代码注释与理解
1 #coding:utf-8 # 日期 2017年9月4日 环境 Python 3.5 TensorFlow 1.3 win10开发环境. import tensorflow as tf from ...
- [Luogu 1410]子序列
Description 给定一个长度为N(N为偶数)的序列,问能否将其划分为两个长度为N/2的严格递增子序列, Input 若干行,每行表示一组数据.对于每组数据,首先输入一个整数N,表示序列的长度. ...
- HDU 4641 K-string
Description Given a string S. K-string is the sub-string of S and it appear in the S at least K time ...
- Linux之grep命令
概述 所有的类linux系统都会提供一个名为grep(global regular expression print,全局正则表达式输出)的搜索工具.grep命令在对一个或多个文件的内容进行基于模式的 ...
- Delphi Inputbox,InputQuery用法
Delphi :InputQuery,InputBox用法及区别 function InputQuery(const ACaption, APrompt: string; var Value: str ...
- python3全栈开发-并发编程,多进程的基本操作
一 .multiprocessing模块介绍 python中的多线程无法利用多核优势,如果想要充分地使用多核CPU的资源(os.cpu_count()查看),在python中大部分情况需要使用多进程. ...
- Spring Boot 2.0系列文章(五):Spring Boot 2.0 项目源码结构预览
关注我 转载请务必注明原创地址为:http://www.54tianzhisheng.cn/2018/04/15/springboot2_code/ 项目结构 结构分析: Spring-boot-pr ...
