首页指南参考教程

共享路由

了解如何使用 Expo Router 定义共享路由或使用数组以不同布局多次使用同一路由。


要将相同的 URL 与不同的布局相匹配,请使用 groups 和重叠的子路由。这种模式在原生应用中非常常见。例如,在 X 应用中,可以在每个选项卡(例如主页、搜索和个人资料)中查看个人资料。然而,访问该路由只需要一个 URL。

¥To match the same URL with different layouts, use groups with overlapping child routes. This pattern is very common in native apps. For example, in the X app, a profile can be viewed in every tab (such as home, search, and profile). However, there is only one URL that is required to access this route.

在下面的示例中,app/_layout.tsx 是标签栏,每个路由都有自己的标题。app/(profile)/[user].tsx 路由在每个选项卡之间共享。

¥In the example below, app/_layout.tsx is the tab bar and each route has its own header. The app/(profile)/[user].tsx route is shared between each tab.

app
_layout.tsx
(home)
  _layout.tsx
  [user].tsx
(search)
  _layout.tsx
  [user].tsx
(profile)
  _layout.tsx
  [user].tsx

重新加载页面时,将渲染第一个字母匹配项。

¥When reloading the page, the first alphabetical match is rendered.

共享路由可以通过在路由中包含群组名称来直接导航。例如,/(search)/baconbrix 导航到 "search" 布局中的 /baconbrix

¥Shared routes can be navigated directly by including the group name in the route. For example, /(search)/baconbrix navigates to /baconbrix in the "search" layout.

数组

¥Arrays

数组语法是原生应用开发所独有的高级概念。

¥Array syntax is an advanced concept that is unique to native app development.

不要使用不同的布局多次定义相同的路由,而是使用数组语法 (,) 来复制组的子级。例如,app/(home,search)/[user].tsx — 在内存中创建 app/(home)/[user].tsxapp/(search)/[user].tsx

¥Instead of defining the same route multiple times with different layouts, use the array syntax (,) to duplicate the children of a group. For example, app/(home,search)/[user].tsx — creates app/(home)/[user].tsx and app/(search)/[user].tsx in memory.

要区分两条路由,请使用布局的 segment 属性:

¥To distinguish between the two routes use a layout's segment prop:

app/(home,search)/_layout.tsx
export default function DynamicLayout({ segment }) {
  if (segment === '(search)') {
    return <SearchStack />;
  }

  return <Stack />;
}