Expo Router 传递路由作为自定义组件Props时出现类型及运行错误
Expo Router 传递路由作为自定义组件Props时出现类型及运行错误
看起来你遇到了Expo Router在传递路由Props时的类型和运行时双重问题,我来帮你拆解解决:
问题原因分析
- 类型错误:你把
route的类型定义成了普通string,但Expo Router的router.push()方法接受的参数是更严格的类型(比如RouterPushInput或RelativePathString),普通字符串不满足它的类型约束,所以VS Code会抛出TS2345错误。 - 运行时错误:这个是类型不匹配导致的连锁问题——当你传入不符合规范的字符串路径时,Expo Router内部解析路径时无法找到预期的
pathname属性,从而抛出Cannot read property 'pathname' of undefined的错误。
具体解决方案
1. 修正Props的类型定义
直接使用Expo Router提供的官方类型来约束route参数,替换原来的string类型:
import React from 'react'; import { View, Text, StyleSheet, Pressable } from 'react-native'; // 导入需要的路由类型 import { useRouter, RouterPushInput } from "expo-router"; // 用RouterPushInput替代string,覆盖所有合法的路由输入类型 type MyComponentProps = { text: string; route: RouterPushInput; }; const ContinueButton: React.FC<MyComponentProps> = ({ text, route }) => { const router = useRouter(); return ( <Pressable style={({ pressed }) => [ styles.button, pressed && styles.buttonPressed, ]} onPress={() => router.push(route)} > <Text style={styles.buttonText}>{text}</Text> </Pressable> ); };
如果你的路由都是相对路径,也可以用更精确的RelativePathString类型来约束,进一步提升类型安全性。
2. 确保传入的路由路径合法
在使用ContinueButton组件时,必须传入Expo Router认可的有效路由路径,比如:
// 绝对路径示例(对应app目录下的路由结构) <ContinueButton text="进入首页" route="/(starting)/home" /> // 相对路径示例(基于当前页面路由跳转) <ContinueButton text="返回上一页" route="../" />
注意:不要传入空字符串、不存在的路由路径,否则依然会触发运行时错误。
3. 可选:添加运行时校验(增强稳定性)
为了避免意外的无效路由传入,可以在组件内部增加简单的校验逻辑:
const ContinueButton: React.FC<MyComponentProps> = ({ text, route }) => { const router = useRouter(); const handlePress = () => { // 校验路由是否有效 if (typeof route === 'string' && route.trim()) { router.push(route); } else { console.warn('传入的路由路径无效,请检查!'); } }; return ( <Pressable style={({ pressed }) => [ styles.button, pressed && styles.buttonPressed, ]} onPress={handlePress} > <Text style={styles.buttonText}>{text}</Text> </Pressable> ); };
总结
通过上述修改,既解决了TypeScript的类型报错问题,也从根源上避免了运行时的路径解析错误——核心就是让route参数的类型和值都符合Expo Router的要求。
备注:内容来源于stack exchange,提问作者krishfish66
相关产品推荐
相关产品推荐

