This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.
共享路由
编辑页面
了解如何定义共享路由,或者使用数组在不同布局中多次使用同一路由,使用 Expo Router。
为匹配相同的 URL 但使用不同的布局,请使用带有重叠子路由的 组。这种模式在原生应用中非常常见。例如,在 X 应用中,个人资料可以在每个标签页中查看(例如主页、搜索和个人资料)。但是,访问此路由只需要一个 URL。
在下面的示例中,src/app/_layout.tsx 是标签栏,并且每个路由都有自己的页眉。src/app/(profile)/[user].tsx 路由会在每个标签页之间共享。
srcapp_layout.tsx(home)_layout.tsx[user].tsx(search)_layout.tsx[user].tsx(profile)_layout.tsx[user].tsx当页面重新加载时,会渲染第一个按字母顺序匹配的结果。
可以通过在路由中包含组名来直接导航到共享路由。例如,/(search)/baconbrix 会在“search”布局中导航到 /baconbrix。
数组
数组语法是一个仅在原生应用开发中才独有的高级概念。
不要为不同的布局多次定义相同的路由,而是使用数组语法 (,) 来复制组的子路由。例如,src/app/(home,search)/[user].tsx — 会在内存中创建 src/app/(home)/[user].tsx 和 src/app/(search)/[user].tsx。
要区分这两个路由,请使用布局的 segment 属性:
export default function DynamicLayout({ segment }) { if (segment === '(search)') { return <SearchStack />; } return <Stack />; }
要启用 数组语法,请在动态布局中使用 unstable_settings 对象,为每个组指定 initialRouteName:
export const unstable_settings = { initialRouteName: 'home', search: { initialRouteName: 'search', }, }; export default function DynamicLayout({ segment }) { %%placeholder-start%% ... %%placeholder-end%% }
在上面的示例中,home 路由是 home 组和应用的默认路由。search 路由是 search 组的默认路由。
要点
- 你只能为当前导航器提供分组。
- 使用数组语法时,如果有两个组(例如,
(one)/(two)),则只使用最后一个组的 segment 来匹配路由。 - 如果至少有两个组的
initialRouteName,但没有提供默认的initialRouteName,则使用第一个组的initialRouteName。