android - React Navigation - 在退出应用程序之前创建确认屏幕
问题描述
我正在使用react-native
and react-navigation
(v5),在 Android 上,后退按钮将弹出每个屏幕,直到没有更多屏幕并退出应用程序。
我想阻止退出并在退出应用程序之前用 yes|no 提示用户,但在退出之前检查navigation.state
orcanGoBack
并没有指出有关最终屏幕的任何线索
BackHandler.addEventListener('hardwareBackPress', () => {
const canGoBack = navigation.canGoBack(); // always false
const isFocused = navigation.isFocused(); // always true
// TODO: how to check if we're on last screen?
// I need to pop until last screen and display confirmation alert
// navigation.state is a whole bunch of whores with no reliable way to check for last screen (I tried the _index_ and _history_
if ( canGoBack && isFocused ) {
navigation.goBack(); // never goes here
return true; // means handled, default behaviour of popping screen won't be executed
}
return false; // not handled, react-navigation will pop screens and when no more screens to pop, will exit app
// return true; // if I return true, no screens will get popped, and no auto-exit app also, but I need the pop until last
}
有谁知道为什么navigation.canGoBack()
总是返回假,如果真的有办法检查剩下多少屏幕?
解决方案
useFocusEffect(
React.useCallback(() => {
const onBackPress = () => {
Alert.alert('Are you sure', 'Do you really want to exit?', [
{
text: 'Cancel',
onPress: () => null,
style: 'cancel',
},
{text: 'YES', onPress: () => BackHandler.exitApp()},
]);
return true;
};
BackHandler.addEventListener('hardwareBackPress', onBackPress);
return () =>
BackHandler.removeEventListener('hardwareBackPress', onBackPress);
}, []),
);
这段代码确实对我有用
推荐阅读
- c# - .NET 4.0 char* 到 x64 0xc0000374 上的字符串互操作崩溃
- bash - Shell 读取 *有时* 会去除尾随分隔符
- python - 它计算数据框每一列中缺失值的总数
- python - 使用 Python3 删除新行
- python-3.x - 为什么导入 matplotlib.pyplot 会改变后端?
- java - 如何从无 gui 类实时更新 Java Jframe 控件
- java - JUnit4 测试期间与数据库的连接
- webpack - webpack - 从命令行关闭手表
- excel - 没有数据传输到带有 ADODB 记录集的 Access
- asp.net - 在asp中用逗号添加数字