首页 > 解决方案 > StackNavigator 的 goBack 与嵌套的 BottomTabNavigator

问题描述

我在 React Native 0.61.x 中使用 React Navigation 5.x。目标是让导航的 goBack 功能表现得像 Android 的默认后退按钮。在下面的示例中,用户登陆个人资料页面,该页面位于 StackNavigator 内。

单击该按钮导航到带有 2 个选项卡的 BottonTabNavigator。在标签之间切换后,我希望 goBack 的行为类似于 Android 的硬件后退按钮,它将用户导航到最后一个可见的标签。当 BottomTabNavigator 的历史堆栈为空时,它会转到 Profile 页面。但是,单击 StackNavigator 标题中的后退箭头会再次导航回起始页面。

我尝试调度 goBack 事件而不是直接调用该函数。我将 null 传递给它,尝试使用路由键值等。是否有任何优雅的解决方案不会让我基本上编写自己的路由逻辑?我知道顶级导航器知道底层导航器的历史和可用路线。

这是工作示例和代码的链接:

https://snack.expo.io/rJ64JkgDI

应用程序.js

import { Text, View, Button } from 'react-native';
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
import { createStackNavigator } from "@react-navigation/stack";
import { NavigationContainer } from '@react-navigation/native';

var Stack = createStackNavigator();
var Tab = createBottomTabNavigator();

function Feed() {
    return <View><Text>Feed</Text></View>;
}

function Profile({navigation}){
  return (
    <View>
      <Text>
        Profile
      </Text>
      <Button title="test" onPress={() => { navigation.navigate("Home")} }></Button>
    </View>);
}

function Home() {
  return (
    <Tab.Navigator>
      <Tab.Screen name="Feed" component={Feed} />
      <Tab.Screen name="Messages" component={Messages} />
    </Tab.Navigator>
  );
}

function Messages() {
  return <View><Text>Messages</Text></View>;
}

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Profile" component={Profile} />
        <Stack.Screen name="Home" component={Home} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

标签: reactjsreact-nativereact-navigationreact-navigation-v5

解决方案


您可以尝试重置堆栈导航或直接调用您想要使用堆栈导航访问的页面,如下所示:

 this.props.navigation.dispatch(
   StackActions.reset({
     index: 0,
     actions: [NavigationActions.navigate({ routeName: "Feed" })]
   })
 );

推荐阅读