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()函数封装后通 ...
随机推荐
- 以太坊如何估计计算gas?
以太坊如何估计估算计算gas?Etherscan上transaction info中有个gas used by txn,结果跟remix给的结果以及geth中getTransactionReceipt ...
- 【实验吧】CTF_Web_简单的SQL注入之3
实验吧第二题 who are you? 很有意思,过两天好好分析写一下.简单的SQL注入之3也很有意思,适合做手工练习,详细分析见下. http://ctf5.shiyanbar.com/web/in ...
- poj 1012——Toseph
提交地址:http://poj.org/problem?id=1012 ...
- Codefroces 850C Arpa and a game with Mojtaba
Description两个人Van♂游戏.给出$n$个正整数$ai$两人轮流操作,每次选出一个素数$p$和一个幂数$k$,选择的前提为该$n$个数中有$p^{k}$的倍数.接着将所有的$p^{k}$的 ...
- 计蒜客NOIP模拟赛4 D1T2小X的密室
小 X 正困在一个密室里,他希望尽快逃出密室. 密室中有 N 个房间,初始时,小 X 在 1 号房间,而出口在 N 号房间. 密室的每一个房间中可能有着一些钥匙和一些传送门,一个传送门会单向地创造一条 ...
- 【BZOJ3531】【SDOI2014】旅行
题目传送门 题目大意:给定一棵无根树,每个节点有自己的类别和权值,现在给定两个类别相同的点,叫你求这2点路径上同类别节点的权值和/最大权值. 节点类别与权值会改变. 解题思路:考虑对每一个类别开一棵线 ...
- ●BZOJ 4516 [Sdoi2016]生成魔咒
题链: http://www.lydsy.com/JudgeOnline/problem.php?id=4516 题解: 把串反过来后,问题变为求每个后缀的互不相同的子串个数.首先用倍增算法求出 sa ...
- k-d树模板(BZOJ2648)
实现了插入一个点,查询距某个位置的最近点. #include <cstdio> #include <algorithm> using namespace std; , inf ...
- 数据挖掘实战<1>:数据质量检查
数据行业有一句很经典的话--"垃圾进,垃圾出"(Garbage in, Garbage out, GIGO),意思就是,如果使用的基础数据有问题,那基于这些数据得到的任何产出都是没 ...
- centos7安装nginx必要环境
安装所需环境 Nginx 是 C语言 开发,建议在 Linux 上运行 , 在安装nginx前还要安装以下的环境包 一. gcc 安装安装 nginx 需要先将官网下载的源码进行编译,编译依赖 gcc ...
