React Navigation TabNavigator:在选项卡更改时重置上一个选项卡 [英] React Navigation TabNavigator: Reset previous tab on tab change
问题描述
我有以下路线结构:
StackNavigator
-StackNavigator
-TabNavigator
--Tab1
---Route 1 (Stack) (initial)
---Route 2 (Stack)
--Tab2
---Route 3 (Stack) (initial)
---Route 4 (Stack)
当我访问 Tab1 ->路线 1 ->路线 2 ->Tab2
并返回到 Tab1
,活动路由是 2 而不是 initialRoute
1.
When I visit Tab1 -> Route 1 -> Route 2 -> Tab2
and go back to Tab1
, the active route is 2 instead of the initialRoute
1.
我正在做以下事情:
tabBarOnPress: ({ scene }) => {
const { route } = scene;
const tabRoute = route.routeName;
const { routeName } = route.routes[0];
navigation.dispatch(NavigationActions.navigate({ routeName: tabRoute }));
navigation.dispatch(NavigationActions.reset({
index: 0,
actions: [
NavigationActions.navigate({ routeName }),
],
}));
},
但问题是它首先显示Route 2
,然后导航到Route 1
.
but the problem is that it first shows Route 2
and then navigate to Route 1
.
如何重置之前的选项卡/屏幕,以便在切换选项卡时始终直接显示初始路线.
How can I reset the previous tab/screens, so when I switch the tab always to show directly the initial route.
推荐答案
5.x.x 版本的解决方案:
将监听器传递给屏幕组件:
Pass a listener to the screen component:
<Tab.Screen
name="homeTab"
component={HomeStackScreen}
listeners={tabBarListeners}
/>
然后在这个监听器上,当用户每次按下标签时导航:
Then on this listener, navigate the user every time when he presses the tab:
const tabBarListeners = ({ navigation, route }) => ({
tabPress: () => navigation.navigate(route.name),
});
来源:https://github.com/react-navigation/react-导航/问题/8583
4.x.x 版的解决方案:
tabBarOnPress: ({ navigation }) => {
navigation.popToTop();
navigation.navigate(navigation.state.routeName);
}
来源:https://github.com/react-navigation/react-导航/问题/1557
版本 2.x.x 和 3.x.x 的解决方案:
问题是,当我重置路线时,我需要传递上一个 routeName(离开选项卡)的导航动作并为下一个路线调度一个新的导航动作:
The problem is that when I reset the route, I need to pass the navigation action of the previous routeName (leaving tab) and to dispatch a new navigation action for the next route:
tabBarOnPress: ({ previousScene, scene }) => {
const tabRoute = scene.route.routeName;
const prevRouteName = previousScene.routes[0].routeName;
navigation.dispatch(NavigationActions.reset({
index: 0,
actions: [
NavigationActions.navigate({
routeName: prevRouteName
}),
],
}));
navigation.dispatch(NavigationActions.navigate({
routeName: tabRoute
}));
}
这篇关于React Navigation TabNavigator:在选项卡更改时重置上一个选项卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!