javascript - react 导航 2 : How to check previous scene and to disable tab change

标签 javascript reactjs react-native react-navigation

我有一个标签导航。我的其中一个选项卡有一个表单,如果我的表单数据未保存,我想禁用导航事件。

在ver.1中,tabBarOnPress方法提供了previousScenescenejumpToIndex,所以我可以检查我要离开的场景并访问它的 Prop 。

现在在ver.2中,tabBarOnPress方法为场景提供了navigation Prop ,但是之前的场景 Prop 不见了:/

navigationOptions: {
    tabBarOnPress: ({ navigation, defaultHandler }) => {
        // Check the previous screen
        // If I am leaving the home screen and the user has unsaved data
        // disable tab navigation
        // else change to the pressed tab
    },
},

此外,我尝试使用导航事件监听器,但 NAVIGATE 操作已被调度:

props.navigation.addListener('willBlur', () => {
    // Disable tab switching;
}),

简单点心:https://snack.expo.io/@hristoeftimov/handle-tab-changes-in-react-navigation-v2

任何解决方案如何在离开标签之前禁用标签切换?

最佳答案

我找到了一种更简单的方法,使用 getStateForAction

const defaultGetStateForAction = MainStack.router.getStateForAction;
MainStack.router.getStateForAction = (action, state) => {
    if (!state) {
        return defaultGetStateForAction(action, state);
    }

    if (
        action.type === NavigationActions.NAVIGATE
        && state.routes[state.index].key === 'HomeTab'
    ) {
        const tab = state.routes[state.index];
        const currentRoute = tab.routes[tab.index];
        const currentRouteParams = currentRoute.params;

        if (currentRouteParams && currentRouteParams.isNavigationDisabled) {
            return currentRouteParams.showConfirmationDialog(action);
        }
    }

    return defaultGetStateForAction(action, state);
}

每次当我在选项卡之间切换时,它都会跳转到 getStateForAction,我可以在其中访问离开选项卡(来自 state)和下一个屏幕(来自 action )。

因此,当我的操作是 NAVIGATE 并且离开屏幕/路线是 HoneTab 时,我可以更改/禁用操作的默认状态并触发 showConfirmationDialog( ) - 这是一个我可以设置为我的 HomeTab 屏幕的路由参数的函数。

关于javascript - react 导航 2 : How to check previous scene and to disable tab change,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53009068/

相关文章:

javascript - 在ReactJS中如何在组件之前加载数据?

android - 安装 react-native-fbsdk 后,react-native run-android 失败并显示 "Task :app:compileDebugJavaWithJavac FAILED"

json - React-Native Rendering json flatlist

android - 无法在 React Native 项目中看到 Android/iOS 文件夹

php - 如何将数组编码为 JSON?

javascript - 在 chrome 中获取 iframe body html 内容

javascript - 按函数映射列表,单击时出现错误 : "Cannot read property ' value' of undefined"

javascript - 如何在return()中调用var

javascript - ExpressJs : Config variables in different environments

php - 使用 xml 将 javascript 变量发布到服务器