我有一个标签导航。我的一个选项卡有一个表单,如果我的表单数据没有保存,我想禁用导航事件。
在版本1中,tabBarOnPress方法提供了previousScene、scene和jumpToIndex,因此我能够检查我要离开的场景并访问它的道具。
在第2版中,tabBarOnPress方法为场景提供了navigation支持,但是缺少了前一个场景支柱:/
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
在离开选项卡之前,如何禁用选项卡切换?
发布于 2018-11-05 08:15:09
我发现了一种更简单的方法,使用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() --这是一个函数,我可以将它设置为HoneTab屏幕的路由参数。
发布于 2018-10-29 19:55:43
navigation对象包含所需的数据,因为它在导航到新选项卡之前保存导航状态。此导航状态既有您要从其中导航的屏幕,也有它的参数。
为了获得状态,可以使用以下函数:
function getCurrentRoute(navState) {
if (!navState) {
return null;
}
const route = navState.routes[navState.index];
if (route.routes) {
return getCurrentRoute(route); // nested routes
} else {
return {
name: route.routeName,
params: { ...route.params }
};
}
}因此,现在可以在onPress处理程序中使用此函数。就像这样:
navigationOptions: {
tabBarOnPress: ({ navigation, defaultHandler }) => {
const currentRoute = getCurrentRoute(navigation.state);
if (currentRoute.name !== 'Home' || !currentRoute.params.isNavigationDisabled) {
defaultHandler();
}
}
}当然,这意味着您需要使用isNavigationDisabled方法在主屏幕中管理名为this.props.navigation.setParams的导航参数。
此外,我希望我的屏幕名称是正确的,如果不只是调试它。
https://stackoverflow.com/questions/53009068
复制相似问题