监听APP当前所处的状态

监听 APP 当前所处的状态 (处于后台还是当前运行状态)

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
<!-- 在APP加载的第一个js入口处  -->

import React, { Component } from 'react';
import { AppState, View, Text } from 'react-native';

export default class App extends Component {

<!-- 在生命周期函数中创建监听函数 -->
componentDidMount() {
AppState.addEventListener('change', this.handleAppStateChange)
}


handleAppStateChange = (currentAppState) => {
if (currentAppState === 'active') {
console.log('我又进来了')
<!-- do something -->
} else {
console.log('现在在后台')
<!-- do something -->
}
}

render() {
console.disableYellowBox = true
return (
<View>
<Text>
我的第一个RN App
</Text>
</View>
);
}
}