嵌套导航器
了解如何在 Expo Router 中嵌套导航器。
警告 导航 UI 元素(Link、Tabs、Stack)可能在将来会从 Expo Router 库中移出。

在屏幕之间导航,在屏幕之间传递参数,创建动态路由,并配置屏幕标题和动画。
嵌套导航器允许在另一个导航器的屏幕内呈现一个导航器。本指南是对 React Navigation: 嵌套导航器 的扩展,适用于 Expo Router。它提供了一个示例,展示了在使用 Expo Router 时嵌套导航器的工作方式。
🌐 Nesting navigators allow rendering a navigator inside the screen of another navigator. This guide is an extension of React Navigation: Nesting navigators to Expo Router. It provides an example of how nesting navigators work when using Expo Router.
示例
🌐 Example
考虑以下用作示例的文件结构:
🌐 Consider the following file structure which is used as an example:
app_layout.tsxindex.tsxhome_layout.tsxfeed.tsxmessages.tsx在上面的例子中,app/home/feed.tsx 匹配 /home/feed,而 app/home/messages.tsx 匹配 /home/messages。
🌐 In the above example, app/home/feed.tsx matches /home/feed, and app/home/messages.tsx matches /home/messages.
import { Stack } from 'expo-router'; export default Stack;
下面的 app/home/_layout.tsx 和 app/index.tsx 都嵌套在 app/_layout.tsx 布局中,因此它们将作为一个堆栈进行渲染。
🌐 Both app/home/_layout.tsx and app/index.tsx below are nested in the app/_layout.tsx layout so that it will be rendered as a stack.
import { Tabs } from 'expo-router'; export default Tabs;
import { Link } from 'expo-router'; export default function Root() { return <Link href="/home/messages">Navigate to nested route</Link>; }
下面的 app/home/feed.tsx 和 app/home/messages.tsx 都嵌套在 home/_layout.tsx 布局中,因此它们将被渲染为一个选项卡。
🌐 Both app/home/feed.tsx and app/home/messages.tsx below are nested in the home/_layout.tsx layout, so it will be rendered as a tab.
import { View, Text } from 'react-native'; export default function Feed() { return ( <View> <Text>Feed screen</Text> </View> ); }
import { View, Text } from 'react-native'; export default function Messages() { return ( <View> <Text>Messages screen</Text> </View> ); }
导航到嵌套导航器中的屏幕
🌐 Navigate to a screen in a nested navigator
在 React Navigation 中,可以通过在 params 中传递屏幕名称来控制导航到特定的嵌套屏幕。这会渲染指定的嵌套屏幕,而不是该嵌套导航器的初始屏幕。
🌐 In React Navigation, navigating to a specific nested screen can be controlled by passing the screen name in params. This renders the specified nested screen instead of the initial screen for that nested navigator.
例如,从 root 导航器的初始屏幕,你想导航到 settings(一个嵌套导航器)中的名为 media 的屏幕。在 React Navigation 中,这可以按下面的示例进行操作:
🌐 For example, from the initial screen inside the root navigator, you want to navigate to a screen called media inside settings (a nested navigator). In React Navigation, this is done as shown in the example below:
navigation.navigate('root', { screen: 'settings', params: { screen: 'media', }, });
在 Expo Router 中,你可以使用 router.push() 来实现相同的效果。无需在参数中显式传递屏幕名称。
🌐 In Expo Router, you can use router.push() to achieve the same result. There is no need to pass the screen name in the params explicitly.
router.push('/root/settings/media');