我有一个标签导航。我的其中一个选项卡有一个表单,如果我的表单数据未保存,我想禁用导航事件。
在ver.1中,tabBarOnPress
方法提供了previousScene
、scene
和jumpToIndex
,所以我可以检查我要离开的场景并访问它的 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/