如何知道React本机应用程序是否进入后台? [英] How to know if a react native app goes to background?
问题描述
是否可以知道RN应用是否已进入后台?有回调或触发器吗?
Is it possible to know if a RN app has gone to background? Any callback or trigger?
如果我收听所在屏幕的 componentDidUnmount
或 componentWillUnmount
,则仅当我返回/返回另一个屏幕时才会触发
If I listen to componentDidUnmount
or componentWillUnmount
of the screen I'm on, it will only be fired if I go back/forth to another screen
推荐答案
您可以收听 appState
事件.来自 https://facebook.github.io/react-native/docs/appstate.html :
You can listen to the appState
event.
From https://facebook.github.io/react-native/docs/appstate.html:
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>
);
}
}
顺便说一句,这将始终显示当前状态为:活动",因为这是该应用对用户可见的唯一状态.
By the way, this will always say 'Current state is: active', because that is the only state in which the app will be visible for the user.
这篇关于如何知道React本机应用程序是否进入后台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!