在React Router v6中,<Link>组件的relative属性有两个可选值:"route"和"path",它们决定了相对路径的解析方式。
| 特性 | relative="route" | relative="path" |
|---|---|---|
| 解析基准 | 当前路由的路径模式 | 当前URL的实际路径 |
| 动态参数 | 会考虑路由参数 | 忽略路由参数 |
| 行为 | 更像编程式导航 | 更像传统HTML链接 |
| 适用场景 | 嵌套路由中更安全 | 简单相对路径时更直观 |
:id)jsx
// 当前URL: /users/123
// 当前路由路径: /users/:id
<Link to="profile" relative="route" />
// 结果: /users/123/profile (保留123参数)jsx
// 当前URL: /users/123
<Link to="profile" relative="path" />
// 结果: /users/profile (忽略123参数)使用route(默认)当:
useNavigate行为一致使用path当:
// 假设当前URL是 /users/123/settings
// 当前路由路径是 /users/:id/settings
<Link to="profile" relative="route" />
// 结果: /users/123/profile (保留id参数)
<Link to="profile" relative="path" />
// 结果: /users/123/profile (与route相同,因为URL和路由模式匹配)
<Link to="../profile" relative="route" />
// 结果: /users/123/profile (向上导航但保留id)
<Link to="../profile" relative="path" />
// 结果: /users/profile (向上导航并忽略id)
理解这个区别可以帮助你在复杂路由结构中更精确地控制导航行为。