如何在反应原生导航时覆盖 backButton 的行为

问题描述

我使用 https://wix.github.io/react-native-navigation/docs/before-you-start/ 为我的 React Native 应用导航。我有一个问题,假设有三个 cmp A、B、C。从 comp A 有一个 history.push() 执行,它重定向到 cmp B,然后 cmp B 是一些路径匹配器,其中根据从 A 推送的路径呈现特定组件,假设 cmp B 匹配路径,然后呈现 C cmp ,其中 C 有这样的:

代码:

              Navigation.push(componentId,{
                component: {
                    id: 'BottomSheetRollupView',name: 'bottomSheet.Rollup',passProps: {
                        component,passProps,},options: {
                        statusBar: {
                            style: Platform.select({android: 'light',ios: 'dark'}),});

所以 C cmp 将一个新屏幕推送到堆栈,所以此时当从导航中单击返回时,我想将我重定向到 A 而不是 B。如何更改后退按钮的行为,或者我可以以某种方式禁用它?按后退按钮当前将我重定向回 cmp B,我不想这样做!

谢谢。

解决方法

您可以使用 navigation.addListener() 更改返回时的行为。我发现它有点笨拙,但它有效 - 在我们的例子中,如果数据丢失,我们会警告返回。我们还必须区分 Save 和 Back 按下,我们通过在按下 Save 按钮时设置状态标志来做到这一点。这是钩子的样子 - 我认为它应该适合您的需求:

// Based on: https://reactnavigation.org/docs/preventing-going-back/
function useAlertOnGoBack({
  hasEdited,didSave,}: {
  hasEdited: boolean;
  didSave: boolean;
}) {
  const navigation = useNavigation();
  useEffect(() => {
    const unsubscribe = navigation.addListener("beforeRemove",e => {
      if (!hasEdited || didSave) {
        // No listener
        return;
      }

      // Prevent default behavior of leaving the screen
      e.preventDefault();

      showExitWithoutSavingAlert(() => navigation.dispatch(e.data.action));
    });

    return unsubscribe;
  },[hasEdited,navigation,didSave]);
}

export function showExitWithoutSavingAlert(dismissScreen: () => void) {
  // Prompt the user before leaving the screen
  Alert.alert("Discard unsaved changes?",undefined,[
    {
      text: "Discard Changes",style: "destructive",// If the user confirmed,then we dispatch the action we blocked earlier
      // This will continue the action that had triggered the removal of the screen
      onPress: dismissScreen,},{ text: "Cancel",style: "cancel",onPress: () => {} },]);
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...