Expo问题:_layout中使用useRouter在Android端无法跳转至设置页
问题:Expo Router头部设置按钮Android端无法跳转,浏览器正常
我在Expo项目的_layout组件中实现了一个头部设置按钮,点击图标按钮本应跳转到/settings页面,但该功能仅在浏览器中生效,Android端点击后无任何反应。
代码如下:
import { Redirect, Stack, useRouter } from "expo-router"; import { TouchableOpacity } from "react-native"; import { Ionicons } from "@expo/vector-icons"; export default function RootLayout() { const router = useRouter(); // Define the redirect function inside the component const redirect = () => { console.log("Navigating to settings"); router.navigate("/settings"); }; return ( <Stack screenOptions={{ headerStyle: { backgroundColor: 'lightblue', }, headerTitleStyle: { fontWeight: 'bold', color: 'white', }, title: 'Weerklank', headerRight: () => ( <TouchableOpacity onPress={redirect} style={{ marginRight: 15 }} > <Ionicons name="settings" size={24} color="white" /> </TouchableOpacity> ) }}> <Stack.Screen name="settings" options={{ title: 'Settings', // Override the title for the settings screen }} /> </Stack> ); }
解决方案
更新Expo Router依赖
部分旧版本的Expo Router存在Android端路由跳转的兼容性问题,执行命令更新到最新稳定版:npx expo install expo-router改用
router.push替代router.navigate
在Android原生环境中,navigate的行为可能不如push稳定,修改跳转逻辑:const redirect = () => { console.log("Navigating to settings"); router.push("/settings"); };确认路由文件存在
确保项目app目录下存在settings.js或settings/index.js文件,Expo Router依赖文件系统映射路由,路径必须严格匹配。替换TouchableOpacity为Pressable
Pressable在Android端的触摸事件处理更可靠,同时可以添加内边距扩大可点击区域:import { Pressable } from "react-native"; // 替换原有TouchableOpacity <Pressable onPress={redirect} style={{ marginRight: 15, padding: 8 }} > <Ionicons name="settings" size={24} color="white" /> </Pressable>清除Expo缓存后重建
Android端缓存可能导致路由逻辑异常,执行以下命令清除缓存并重启项目:npx expo start --clear
内容的提问来源于stack exchange,提问作者kersjan14
相关产品推荐
相关产品推荐

