React-Native
来源:互联网 发布:telnet 内网端口不通 编辑:程序博客网 时间:2024/06/05 17:54
有时我们需要知道应用当前的运行状态,这样我们可以根据不同的状态进行相应的操作。React Native 提供了 AppState 来告知我们 App 当前的状态:激活(前台运行中)、还是后台运行。甚至可以通知我们状态的改变。下面分别对这两种情况进行介绍。
1,主动获取当前应用状态
我们可以使用 AppState.currentState 来获取应用的状态,返回值如下:
active:前台运行中
background:后台运行中
inactive:运行的过渡状态
- (1)效果图
点击按钮后,将当前状态显示出来。
- (2)样例代码
import React, { Component } from 'react';import { AppRegistry, StyleSheet, Text, View, AppState} from 'react-native';//默认应用的容器组件class App extends Component { render() { return ( <View style={styles.container}> <Text style={styles.item} onPress={this.getCurrentState.bind(this)}> 获取当前状态 </Text> </View> ); } //获取当前状态 getCurrentState() { alert("当前状态:" + AppState.currentState) } }//样式定义const styles = StyleSheet.create({ container:{ flex: 1, marginTop:25 }, item:{ marginTop:10, marginLeft:5, marginRight:5, height:30, borderWidth:1, padding:6, borderColor:'#ddd', textAlign:'center' },});AppRegistry.registerComponent('HelloWorld', () => App);
2,监听状态的变化
我们可以在代码中添加相关的事件监听:
AppState.addEventListener:用于添加事件监听
AppState.removeEventListener:用于删除事件监听
- (1)效果图
程序启动后会自动监听状态改变事件、以及内存报警事件。按 home 键将 App 退到后台,接着再回到前台运行可以看到效果。
- (2)样例代码
import React, { Component } from 'react';import { AppRegistry, StyleSheet, Text, View, AppState} from 'react-native';//默认应用的容器组件class App extends Component { componentWillMount() { //监听状态改变事件 AppState.addEventListener('change', this.handleAppStateChange); //监听内存报警事件 AppState.addEventListener('memoryWarning', function(){ console.log("内存报警...."); }); } componentWillUnmount() { //删除状态改变事件监听 AppState.removeEventListener('change', this.handleAppStateChange); } render() { return ( <View style={styles.container}> <Text style={styles.item}>监听中...</Text> </View> ); } //状态改变响应 handleAppStateChange(appState) { alert('当前状态为:'+appState); } }//样式定义const styles = StyleSheet.create({ container:{ flex: 1, marginTop:25 }, item:{ marginTop:10, marginLeft:5, marginRight:5, height:30, borderWidth:1, padding:6, borderColor:'#ddd', textAlign:'center' },});AppRegistry.registerComponent('HelloWorld', () => App);
阅读全文
0 0
- react native
- React Native
- React Native
- React- Native
- react-native
- React Native
- React Native
- react native
- React Native
- react-native
- React Native
- react native
- React Native
- React Native
- React Native
- React Native
- react native
- React Native
- 关于make update-api命令
- Linux下安装php
- VC 使用OnCtlColor函数来改变控件颜色
- for循环的闭包
- Android FloatMath.ceil过时的解决办法
- React-Native
- 通用串口类
- cordova自定义插件步骤
- SRS(simple-rtmp-server)流媒体服务器源码分析--启动
- Navicat for MySQL使用手记--实现自动备份数据库
- Unity3D 04-GameObject,Component,Time,Input,Physics
- 工作中遇到的一些问题集合
- 作为前端,应该知道什么是‘单元测试’?
- jsp项目web实战