共享路由
了解如何使用 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].tsx
和 app/(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:
export default function DynamicLayout({ segment }) {
if (segment === '(search)') {
return <SearchStack />;
}
return <Stack />;
}
要启用数组语法,请在动态布局中使用 unstable_settings
对象为每个组指定 initialRouteName
:
¥To enable the array syntax, specify the initialRouteName
for each group using unstable_settings
object in the dynamic layout:
export const unstable_settings = {
initialRouteName: 'home',
search: {
initialRouteName: 'search',
},
};
export default function DynamicLayout({ segment }) {
%%placeholder-start%% ... %%placeholder-end%%
}
在上面的示例中,home
路由是 home
组和应用的默认路由。search
路由是 search
组的默认路由。
¥In the above example, the home
route is the default route for the home
group and the app. The search
route is the default route for the search
group.
关键点
¥Key points
-
你只能为当前导航器提供组。
¥You can only provide groups for the current navigator.
-
使用数组语法时,如果有两个组(例如
(one)/(two)
),则只有最后一个组的段用于匹配路由。¥When using the array syntax, if there are two groups (for example,
(one)/(two)
), only the last group's segment is used for matching the route. -
如果至少有两个组
initialRouteNames
,但未提供默认initialRouteName
,则使用第一个组的initialRouteName
。¥If there are at least two group
initialRouteNames
, but a defaultinitialRouteName
is not provided, the first group'sinitialRouteName
is used.