如何检测OnResume和onPause对原生Es6的反应

时间:2018-04-25 10:47:55

标签: android react-native-android onresume onpause

如何检测从背景到前景es6的任何方法?

这在React-native中是否可行?是否有任何类或工具可以帮助这种方法?

1 个答案:

答案 0 :(得分:2)

试试这个,它适合我

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

class AppStateExample extends Component {

  state = {
    appState: AppState.currentState
  }

  componentDidMount() {
    AppState.addEventListener('change', this._handleAppStateChange);
  }

  componentWillUnmount() {
    AppState.removeEventListener('change', this._handleAppStateChange);
  }

  _handleAppStateChange = (nextAppState) => {
    if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
      console.log('App has come to the foreground!')
    }
    this.setState({appState: nextAppState});
  }

  render() {
    return (
      <Text>Current state is: {this.state.appState}</Text>
    );
  }

}