在 React Router v6 中,<Link> 组件的 relative 属性用于控制链接的相对路径解析方式。relative 属性有两个可选值:'route' 和 'path'。它们的区别主要体现在如何解析相对路径上。
relative="route"(默认值)relative="route"。<Routes>
<Route path="dashboard" element={<Dashboard />}>
<Route path="settings" element={<Settings />} />
</Route>
</Routes>
// 假设当前路由是 /dashboard/settings
<Link to="profile" relative="route">Go to Profile</Link>
to="profile" 会被解析为 /dashboard/profile,因为它是相对于当前路由 /dashboard/settings 的。relative="path"relative="path"。<Routes>
<Route path="dashboard" element={<Dashboard />}>
<Route path="settings" element={<Settings />} />
</Route>
</Routes>
// 假设当前路由是 /dashboard/settings
<Link to="profile" relative="path">Go to Profile</Link>
to="profile" 会被解析为 /dashboard/settings/profile,因为它是相对于当前 URL /dashboard/settings 的。relative="route":相对路径基于当前路由的路径进行解析,适合在嵌套路由中使用。relative="path":相对路径基于当前 URL 的路径进行解析,适合在非嵌套路由或需要基于 URL 路径进行导航的场景中使用。根据你的应用场景选择合适的 relative 模式,可以更灵活地控制导航行为。