跳转到正文
返回

监听 React Native 应用状态

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

<!-- 在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>
    );
  }
}