You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Expo router.push仅直接传字符串生效,传props字符串报错求助

Expo Router 路由跳转传参报错解决方法

问题场景

直接给router.push()传入字符串路径时功能正常:

<Button onPress={() => router.push("../chat/index")}>
    Select
</Button>

但通过props传递字符串路径,或是改用{ pathname: href }对象形式传入时,均触发路由报错(错误提示:The path must start with /, ./, or ../)。

相关代码示例:

interface Props {
    href: string
}

<Button onPress={() => router.push(href)}>
    Select
</Button>

当前使用版本:

"expo": "~50.0.8",
"expo-router": "~3.4.8"

解决方法

1. 严格校验传入路径的格式

Expo Router要求跳转路径必须以/、./或../开头,确保父组件传递href时严格遵循该规则,比如传递"../chat/index"而非"chat/index"这类缺失前缀的路径。

2. 给Props添加类型约束(TypeScript环境)

通过TypeScript的模板字面量类型,提前约束href的格式,避免传入不符合要求的路径:

import { router } from 'expo-router';

interface Props {
  href: `/${string}` | `./${string}` | `../${string}`;
}

const CustomButton = ({ href }: Props) => {
  return <Button onPress={() => router.push(href)}>Select</Button>;
};

3. 增加运行时校验(可选)

如果担心类型约束被绕过,可以在跳转前增加格式校验:

const handlePress = () => {
  if (!/^(\/|\.\/|\.\.\/)/.test(href)) {
    console.error('路径格式错误,必须以/, ./或../开头');
    return;
  }
  router.push(href);
};

4. 改用绝对路径

相对路径容易出现层级问题,可直接使用基于路由根目录的绝对路径,比如"/chat/index",传递和跳转时更稳定:

// 父组件调用时传递绝对路径
<CustomButton href="/chat/index" />

内容的提问来源于stack exchange,提问作者belligol

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 16:33:20