仅当我在主页(屏幕)上并单击“后退”按钮时,我才需要退出react-native应用程序,虽然我已经编写了代码,但它从每个屏幕退出了该应用程序。我正在使用Router-Flux进行路由,请有人帮助我解决问题,到目前为止,我已经尝试过:
componentDidMount = async () => {
BackHandler.addEventListener("hardwareBackPress", this.handleBackPress);
}
componentWillUnmount() {
BackHandler.removeEventListener("hardwareBackPress",
this.handleBackPress);
}
handleBackPress = () => {
Alert.alert(
'Exit App',
'Do you want to exit?',
[
{text: 'No', onPress: () => console.log('Cancel Pressed'), style:
'cancel'},
{text: 'Yes', onPress: () => BackHandler.exitApp()},
],
{ cancelable: false });
return true;
};
Code in my component Homepage.js
import { BackHandler, Alert} from 'react-native';
componentDidMount = async () => {
BackHandler.addEventListener("hardwareBackPress", this.handleBackPress);
}
componentWillUnmount() {
BackHandler.removeEventListener("hardwareBackPress",
this.handleBackPress);
}
handleBackPress = () => {
Alert.alert(
'Exit App',
'Do you want to exit?',
[
{text: 'No', onPress: () => console.log('Cancel Pressed'), style:
'cancel'},
{text: 'Yes', onPress: () => BackHandler.exitApp()},
],
{ cancelable: false });
return true;
};
Code in my Routes.js
import { Router, Stack, Scene } from 'react-native-router-flux';
<Router>
<Stack key="root" hideNavBar={true}>
<Scene key="login" component={Login} title="Login" initial={true} />
<Scene key="homepage" component={Homepage} title="Home" />
<Scene key="history" component={HistoryAll} title="HistoryAll" />
</Stack>
</Router>
I was expecting that when I am on Homepage.Js and click on back button it
will exit the app, its happening but it exits the App from every screen
of the app.
答案 0 :(得分:0)
您可以使用Actions.state.index
作为支票。如果等于1,则退出应用程序,否则,您可以根据需要pop()
或使用任何其他功能。
onBackPress() {
if (Actions.state.index === 1) {
BackHandler.exitApp();
return false;
}
Actions.pop();
return true;
}
希望有帮助!