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()函数封装后通 ...
随机推荐
- thymeleaf-迭代
迭代 1.迭代基础 要在/WEB-INF/templates/product/list.html页面中显示产品,将使用一个表格.都将显示在一行(一个<tr>元素),所以对于我们的模板,我们 ...
- [WC 2014]紫荆花之恋
Description 强强和萌萌是一对好朋友.有一天他们在外面闲逛,突然看到前方有一棵紫荆树.这已经是紫荆花飞舞的季节了,无数的花瓣以肉眼可见的速度从紫荆树上长了出来. 仔细看看的话,这个大树实际上 ...
- ●BZOJ 4596 [Shoi2016]黑暗前的幻想乡
题链: http://www.lydsy.com/JudgeOnline/problem.php?id=4596 题解: 容斥,矩阵树定理,矩阵行列式 先说说容斥:(一共有 N-1个公司) 令 f[i ...
- UVA11552:Fewest Flops
发现如果只有一块就是种类的数目,也就是同种放在一起, 再考虑多块,如果违背的上面的规律,可以发现不会更优, 于是问题就是求在满足同种类放在一起的前提下,尽量使得相邻块的两端一模一样 然后dp一下就可以 ...
- [WC2008]游览计划
[题目描述] 从未来过绍兴的小 D 有幸参加了Winter Camp 2008,他被这座历史名城的秀丽风景所吸引,强烈要求游览绍兴及其周边的所有景点. 主办者将绍兴划分为 N 行M 列(N×M)个方块 ...
- bzoj1492[NOI2007]货币兑换Cash cdq分治+斜率优化dp
1492: [NOI2007]货币兑换Cash Time Limit: 5 Sec Memory Limit: 64 MBSubmit: 5541 Solved: 2228[Submit][Sta ...
- bzoj3295[Cqoi2011]动态逆序对 树套树
3295: [Cqoi2011]动态逆序对 Time Limit: 10 Sec Memory Limit: 128 MBSubmit: 5987 Solved: 2080[Submit][Sta ...
- linux安装ftp
安装vsftpd 1.以管理员(root)身份执行以下命令 1. yum install vsftpd 2.设置开机启动vsftpd ftp服务 1. chkconfig vsftpd on 3. ...
- c# 判断datatable中是否存在某列
if (datatable.columns.contains("要找的列名"))
- npm ERR! Windows_NT 10.0.10586
安装vue脚手架时候一直失败,如图: npm cache clean 管理员下安装: 快捷键 win +x , 按A进入:
