reactjs - 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>
);
}
解决方案
您可以尝试重置堆栈导航或直接调用您想要使用堆栈导航访问的页面,如下所示:
this.props.navigation.dispatch(
StackActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: "Feed" })]
})
);
推荐阅读
- debugging - 调试部署在 Azure Kubernetes 服务中的正在运行的 Windows 容器
- r - Caret 的 train.recipe 似乎没有应用配方程序来删除 NA,随后交叉验证失败
- html - 在 Flutter 中从网站发布用户名和密码
- python - 尝试单击 CheckBox 时出现“元素单击被拦截”错误
- java - 如何从 Java 文本文件中解析像“1.8400e-016”这样的数字?
- python - Pandas 指定 read_csv() 类型推理的优先顺序或列表
- powerquery - PowerQuery 填充缺失的日期和数据
- python - Win.blit 参数一个必须是表面而不是元组,但它是一个正在运行的精灵?
- c# - 为图像/x-xbitmap mime 类型正确的 ImageFormat
- android - 如何解决由 com.google.firebase:firebase-ml-vision:24.0.0 引起的重复类异常