我可以使用以下代码知道何时在屏幕上显示场景:
this.subs = [
this.props.navigation.addListener('didFocus', this.loadOfflineData)
];
但是,如果我想检测场景何时失焦。我想知道该怎么办。
基本上我想检测用户是否按下主页按钮,然后执行一些操作。
任何建议。
答案 0 :(得分:1)
我已经使用android生命周期在android和java中完成了此操作。这应该可以在React Native中工作(请参见下面的EDIT)。 developer.android.com论坛:this page
简而言之:
您应使用onPause()
在Java中有一些代码片段:
@Override
public void onPause() {
super.onPause();
//do something
}
编辑:
This answer告诉您如何在Reacte Native中检测onPause和onResume。
该答案中的代码:
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>
);
}
}
答案 1 :(得分:0)
您可以使用AppState知道何时将应用程序置于后台。
AppState
可以告诉您应用是在前台还是在后台,并在状态更改时通知您。
这是使用AppState的简单示例:
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!');
} else {
console.log('App has gone to the background!');
// start your background task here
}
this.setState({appState: nextAppState});
};
render() {
return <Text>Current state is: {this.state.appState}</Text>;
}
}