带嵌套BottomTabNavigator的StackNavigator的goBack

时间:2020-03-31 21:17:10

标签: reactjs react-native react-navigation react-navigation-v5

我在React Native 0.61.x中使用React Navigation5.x。目标是使导航的goBack功能像Android的默认后退按钮一样工作。 在下面的示例中,用户登录到StackNavigator内部的“个人资料”页面。

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

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

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

https://snack.expo.io/rJ64JkgDI

App.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>
  );
}

1 个答案:

答案 0 :(得分:0)

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

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