Skip to main content
Version: 6.x

抽屉导航器

抽屉导航器在屏幕一侧呈现一个导航抽屉,可以通过手势打开和关闭。

¥Drawer Navigator renders a navigation drawer on the side of the screen which can be opened and closed via gestures.

这封装了 react-native-drawer-layout。如果你想在不集成 React Navigation 的情况下使用抽屉,请直接使用该库。

¥This wraps react-native-drawer-layout. If you want to use the drawer without React Navigation integration, use the library directly instead.

安装

¥Installation

要使用此导航器,请确保你有 @react-navigation/native 及其依赖(遵循本指南),然后安装 @react-navigation/drawer

¥To use this navigator, ensure that you have @react-navigation/native and its dependencies (follow this guide), then install @react-navigation/drawer:

npm install @react-navigation/drawer

然后,你需要安装和配置抽屉导航器所需的库:

¥Then, you need to install and configure the libraries that are required by the drawer navigator:

  1. 首先,安装 react-native-gesture-handlerreact-native-reanimated

    ¥First, install react-native-gesture-handler and react-native-reanimated.

    如果你有 Expo 托管项目,请在项目目录中运行:

    ¥If you have a Expo managed project, in your project directory, run:

    npx expo install react-native-gesture-handler react-native-reanimated

    如果你有一个裸露的 React Native 项目,请在项目目录中运行:

    ¥If you have a bare React Native project, in your project directory, run:

    npm install react-native-gesture-handler react-native-reanimated

    Drawer 支持 Reanimated 1 和最新版本的 Reanimated。如果你想使用最新版本的 Reanimated,请确保按照 安装指南.1 进行配置。

    ¥The Drawer supports both Reanimated 1 and the latest version of Reanimated. If you want to use the latest version of Reanimated, make sure to configure it following the installation guide.

  2. 要完成 react-native-gesture-handler 的安装,请在条目文件的顶部添加以下内容(确保它位于顶部且前面没有其他内容),例如 index.jsApp.js

    ¥To finalize installation of react-native-gesture-handler, add the following at the top (make sure it's at the top and there's nothing else before it) of your entry file, such as index.js or App.js:

    import 'react-native-gesture-handler';

    :::warning 警告

    如果你正在为 Android 或 iOS 进行构建,请不要跳过此步骤,否则即使你的应用在开发中运行良好,也可能会在生产中崩溃。这不适用于其他平台。

    ¥If you are building for Android or iOS, do not skip this step, or your app may crash in production even if it works fine in development. This is not applicable to other platforms.

    :::

  3. 如果你使用的是 Mac 并针对 iOS 进行开发,则还需要安装 pod(通过 可可足类)来完成链接。

    ¥If you're on a Mac and developing for iOS, you also need to install the pods (via Cocoapods) to complete the linking.

npx pod-install ios

API 定义

¥API Definition

要使用此抽屉式导航器,请从 @react-navigation/drawer 导入它:

¥To use this drawer navigator, import it from @react-navigation/drawer:

import { createDrawerNavigator } from '@react-navigation/drawer';

const Drawer = createDrawerNavigator();

function MyDrawer() {
return (
<Drawer.Navigator>
<Drawer.Screen name="Feed" component={Feed} />
<Drawer.Screen name="Article" component={Article} />
</Drawer.Navigator>
);
}
注意

如需完整的使用指南,请访问 抽屉式导航

¥For a complete usage guide please visit Drawer Navigation.

属性

¥Props

Drawer.Navigator 组件接受以下属性:

¥The Drawer.Navigator component accepts following props:

id

导航器的可选唯一 ID。这可以与 navigation.getParent 一起使用来在子导航器中引用该导航器。

¥Optional unique ID for the navigator. This can be used with navigation.getParent to refer to this navigator in a child navigator.

initialRouteName

导航器首次加载时渲染的路由名称。

¥The name of the route to render on the first load of the navigator.

screenOptions

用于导航器屏幕的默认选项。

¥Default options to use for the screens in the navigator.

backBehavior

这控制在导航器中调用 goBack 时发生的情况。这包括在 Android 上按设备的后退按钮或后退手势。

¥This controls what happens when goBack is called in the navigator. This includes pressing the device's back button or back gesture on Android.

它支持以下值:

¥It supports the following values:

  • firstRoute - 返回导航器中定义的第一个屏幕(默认)

    ¥firstRoute - return to the first screen defined in the navigator (default)

  • initialRoute - 返回 initialRouteName prop 中传入的初始屏幕,如果不传则默认到第一屏幕

    ¥initialRoute - return to initial screen passed in initialRouteName prop, if not passed, defaults to the first screen

  • order - 返回到聚焦屏幕之前定义的屏幕

    ¥order - return to screen defined before the focused screen

  • history - 返回导航器中上次访问的屏幕;如果多次访问同一屏幕,较旧的条目将从历史记录中删除

    ¥history - return to last visited screen in the navigator; if the same screen is visited multiple times, the older entries are dropped from the history

  • none - 不处理后退按钮

    ¥none - do not handle back button

defaultStatus

抽屉默认状态 - 抽屉默认是 open 还是 closed

¥The default status of the drawer - whether the drawer should stay open or closed by default.

当此项设置为 open 时,抽屉将从初始渲染中打开。它可以使用手势或以编程方式正常关闭。然而,当回去时,如果抽屉是关闭的,它会重新打开。这本质上与抽屉的默认行为相反,抽屉从 closed 开始,后退按钮关闭打开的抽屉。

¥When this is set to open, the drawer will be open from the initial render. It can be closed normally using gestures or programmatically. However, when going back, the drawer will re-open if it was closed. This is essentially the opposite of the default behavior of the drawer where it starts closed, and the back button closes an open drawer.

detachInactiveScreens

布尔值用于指示是否应从视图层次结构中分离非活动屏幕以节省内存。这使得能够与 react-native-screens 集成。默认为 true

¥Boolean used to indicate whether inactive screens should be detached from the view hierarchy to save memory. This enables integration with react-native-screens. Defaults to true.

useLegacyImplementation

是否使用基于 Reanimated 1 的遗留实现。基于 Reanimated 2 的新实现会表现更好,但需要额外的配置,并且需要使用 Hermes 和 Flipper 来调试。

¥Whether to use the legacy implementation based on Reanimated 1. The new implementation based on Reanimated 2 will perform better, but you need additional configuration and need to use Hermes with Flipper to debug.

在以下情况下默认为 true

¥This defaults to true in the following cases:

  • 复活 2 未配置

    ¥Reanimated 2 is not configured

  • 应用已连接到 Chrome 调试器(Reanimated 2 无法与 Chrome 调试器一起使用)

    ¥App is connected to Chrome debugger (Reanimated 2 cannot be used with Chrome debugger)

  • 应用正在网络上运行

    ¥App is running on Web

否则默认为 false

¥Otherwise, it defaults to false

drawerContent

返回 React 元素以呈现为抽屉内容的函数,例如导航项

¥Function that returns React element to render as the content of the drawer, for example, navigation items

内容组件默认接收以下属性:

¥The content component receives the following props by default:

  • state - 导航仪的 导航状态

    ¥state - The navigation state of the navigator.

  • navigation - 导航器的导航对象。

    ¥navigation - The navigation object for the navigator.

  • descriptors - 包含抽屉屏幕选项的描述符对象。这些选项可以在 descriptors[route.key].options 访问。

    ¥descriptors - An descriptor object containing options for the drawer screens. The options can be accessed at descriptors[route.key].options.

提供定制 drawerContent

¥Providing a custom drawerContent

抽屉的默认组件是可滚动的,并且仅包含 RouteConfig 中路由的链接。你可以轻松覆盖默认组件,以将页眉、页脚或其他内容添加到抽屉中。默认内容组件导出为 DrawerContent。它在 ScrollView 内呈现 DrawerItemList 组件。

¥The default component for the drawer is scrollable and only contains links for the routes in the RouteConfig. You can easily override the default component to add a header, footer, or other content to the drawer. The default content component is exported as DrawerContent. It renders a DrawerItemList component inside a ScrollView.

默认情况下,抽屉是可滚动的并支持带有凹口的设备。如果你自定义内容,你可以使用 DrawerContentScrollView 来自动处理:

¥By default, the drawer is scrollable and supports devices with notches. If you customize the content, you can use DrawerContentScrollView to handle this automatically:

import {
DrawerContentScrollView,
DrawerItemList,
} from '@react-navigation/drawer';

function CustomDrawerContent(props) {
return (
<DrawerContentScrollView {...props}>
<DrawerItemList {...props} />
</DrawerContentScrollView>
);
}

要在抽屉中添加其他项目,你可以使用 DrawerItem 组件:

¥To add additional items in the drawer, you can use the DrawerItem component:

function CustomDrawerContent(props) {
return (
<DrawerContentScrollView {...props}>
<DrawerItemList {...props} />
<DrawerItem
label="Help"
onPress={() => Linking.openURL('https://mywebsite.com/help')}
/>
</DrawerContentScrollView>
);
}

DrawerItem 组件接受以下属性:

¥The DrawerItem component accepts the following props:

  • label(必填):项目的标签文本。可以是字符串,也可以是返回 React 元素的函数。例如 ({ focused, color }) => <Text style={{ color }}>{focused ? 'Focused text' : 'Unfocused text'}</Text>

    ¥label (required): The label text of the item. Can be string, or a function returning a react element. e.g. ({ focused, color }) => <Text style={{ color }}>{focused ? 'Focused text' : 'Unfocused text'}</Text>.

  • icon:显示项目的图标。接受返回 React 元素的函数。例如 ({ focused, color, size }) => <Icon color={color} size={size} name={focused ? 'heart' : 'heart-outline'} />

    ¥icon: Icon to display for the item. Accepts a function returning a react element. e.g. ({ focused, color, size }) => <Icon color={color} size={size} name={focused ? 'heart' : 'heart-outline'} />.

  • focused:布尔值,指示是否将抽屉项目高亮为活动状态。

    ¥focused: Boolean indicating whether to highlight the drawer item as active.

  • onPress(必填):按下时执行的函数。

    ¥onPress (required): Function to execute on press.

  • activeTintColor:项目处于活动状态时图标和标签的颜色。

    ¥activeTintColor: Color for the icon and label when the item is active.

  • inactiveTintColor:项目处于非活动状态时图标和标签的颜色。

    ¥inactiveTintColor: Color for the icon and label when the item is inactive.

  • activeBackgroundColor:项目处于活动状态时的背景颜色。

    ¥activeBackgroundColor: Background color for item when it's active.

  • inactiveBackgroundColor:项目处于非活动状态时的背景颜色。

    ¥inactiveBackgroundColor: Background color for item when it's inactive.

  • labelStyle:标签 Text 的样式对象。

    ¥labelStyle: Style object for the label Text.

  • style:封装器 View 的样式对象。

    ¥style: Style object for the wrapper View.

progress 对象可用于在 drawerContent 中执行有趣的动画,例如抽屉内容的视差运动:

¥The progress object can be used to do interesting animations in your drawerContent, such as parallax motion of the drawer contents:

function CustomDrawerContent(props) {
const progress = useDrawerProgress();

// If you are on react-native-reanimated 1.x, use `Animated.interpolate` instead of `Animated.interpolateNode`
const translateX = Animated.interpolateNode(progress, {
inputRange: [0, 1],
outputRange: [-100, 0],
});

return (
<Animated.View style={{ transform: [{ translateX }] }}>
{/* ... drawer contents */}
</Animated.View>
);
}

如果你使用 Reanimated 1(请参阅 useLegacyImplementation),则 progress 对象是 Reanimated Node,否则是 SharedValue。它代表抽屉的动画位置(0 为关闭;1 为打开)。

¥The progress object is a Reanimated Node if you're using Reanimated 1 (see useLegacyImplementation), otherwise a SharedValue. It represents the animated position of the drawer (0 is closed; 1 is open).

请注意,你不能在 drawerContent 内部使用 useNavigation 钩子,因为 useNavigation 只能在屏幕内部使用。你将获得 drawerContentnavigation 属性,你可以使用它来代替:

¥Note that you cannot use the useNavigation hook inside the drawerContent since useNavigation is only available inside screens. You get a navigation prop for your drawerContent which you can use instead:

function CustomDrawerContent({ navigation }) {
return (
<Button
title="Go somewhere"
onPress={() => {
// Navigate using the `navigation` prop that you received
navigation.navigate('SomeScreen');
}}
/>
);
}

要使用自定义组件,我们需要将其传递到 drawerContent 属性中:

¥To use the custom component, we need to pass it in the drawerContent prop:

<Drawer.Navigator drawerContent={(props) => <CustomDrawerContent {...props} />}>
{/* screens */}
</Drawer.Navigator>

选项

¥Options

以下 options 可用于配置导航器中的屏幕。这些可以在 Drawer.navigatorscreenOptions 属性或 Drawer.Screenoptions 属性下指定。

¥The following options can be used to configure the screens in the navigator. These can be specified under screenOptions prop of Drawer.navigator or options prop of Drawer.Screen.

title

可用作 headerTitledrawerLabel 后备的通用标题。

¥A generic title that can be used as a fallback for headerTitle and drawerLabel.

lazy

该屏幕是否应在第一次访问时呈现。默认为 true。如果你想在初始渲染时渲染屏幕,请将其设置为 false

¥Whether this screen should render the first time it's accessed. Defaults to true. Set it to false if you want to render the screen on initial render.

drawerLabel

给定 { focused: boolean, color: string } 的字符串或函数返回一个 React.Node,以显示在抽屉侧边栏中。未定义时,使用场景 title

¥String or a function that given { focused: boolean, color: string } returns a React.Node, to display in drawer sidebar. When undefined, scene title is used.

drawerIcon

函数,给定 { focused: boolean, color: string, size: number } 返回一个 React.Node 以显示在抽屉侧边栏中。

¥Function, that given { focused: boolean, color: string, size: number } returns a React.Node to display in drawer sidebar.

drawerActiveTintColor

抽屉中活动项目的图标和标签的颜色。

¥Color for the icon and label in the active item in the drawer.

drawerActiveBackgroundColor

抽屉中活动项目的背景颜色。

¥Background color for the active item in the drawer.

drawerInactiveTintColor

抽屉中非活动项目的图标和标签的颜色。

¥Color for the icon and label in the inactive items in the drawer.

drawerInactiveBackgroundColor

抽屉中非活动项目的背景颜色。

¥Background color for the inactive items in the drawer.

drawerItemStyle

单个项目的样式对象,可以包含图标和/或标签。

¥Style object for the single item, which can contain an icon and/or a label.

drawerLabelStyle

应用于呈现标签的内容部分内的 Text 样式的样式对象。

¥Style object to apply to the Text style inside content section which renders a label.

drawerContentContainerStyle

ScrollView 中内容部分的样式对象。

¥Style object for the content section inside the ScrollView.

drawerContentStyle

封装视图的样式对象。

¥Style object for the wrapper view.

drawerStyle

抽屉组件的样式对象。你可以在此处传递抽屉的自定义背景颜色或自定义宽度。

¥Style object for the drawer component. You can pass a custom background color for a drawer or a custom width here.

<Drawer.Navigator
screenOptions={{
drawerStyle: {
backgroundColor: '#c6cbef',
width: 240,
},
}}
>
{/* screens */}
</Drawer.Navigator>

drawerPosition

选项为 leftright。LTR 语言默认为 left,RTL 语言默认为 right

¥Options are left or right. Defaults to left for LTR languages and right for RTL languages.

drawerType

抽屉的类型。它决定抽屉的外观和动画效果。

¥Type of the drawer. It determines how the drawer looks and animates.

  • front:传统的抽屉,用覆盖层覆盖屏幕。

    ¥front: Traditional drawer which covers the screen with an overlay behind it.

  • back:滑动时抽屉会显示在屏幕后面。

    ¥back: The drawer is revealed behind the screen on swipe.

  • slide:屏幕和抽屉都会滑动以显示抽屉。

    ¥slide: Both the screen and the drawer slide on swipe to reveal the drawer.

  • permanent:永久抽屉显示为侧边栏。对于在大屏幕上始终可见的抽屉很有用。

    ¥permanent: A permanent drawer is shown as a sidebar. Useful for having always visible drawer on larger screens.

在 iOS 上默认为 slide,在其他平台上默认为 front

¥Defaults to slide on iOS and front on other platforms.

你可以有条件地指定 drawerType 在较大屏幕上显示永久抽屉,在小屏幕上显示传统抽屉抽屉:

¥You can conditionally specify the drawerType to show a permanent drawer on bigger screens and a traditional drawer drawer on small screens:

import { useWindowDimensions } from 'react-native';
import { createDrawerNavigator } from '@react-navigation/drawer';

const Drawer = createDrawerNavigator();

function MyDrawer() {
const dimensions = useWindowDimensions();

return (
<Drawer.Navigator
screenOptions={{
drawerType: dimensions.width >= 768 ? 'permanent' : 'front',
}}
>
{/* Screens */}
</Drawer.Navigator>
);
}

你还可以根据屏幕尺寸指定其他属性(例如 drawerStyle)来自定义行为。例如,你可以将其与 defaultStatus="open" 结合起来实现主从布局:

¥You can also specify other props such as drawerStyle based on screen size to customize the behavior. For example, you can combine it with defaultStatus="open" to achieve a master-detail layout:

import { useWindowDimensions } from 'react-native';
import { createDrawerNavigator } from '@react-navigation/drawer';

const Drawer = createDrawerNavigator();

function MyDrawer() {
const dimensions = useWindowDimensions();

const isLargeScreen = dimensions.width >= 768;

return (
<Drawer.Navigator
defaultStatus="open"
screenOptions={{
drawerType: isLargeScreen ? 'permanent' : 'back',
drawerStyle: isLargeScreen ? null : { width: '100%' },
overlayColor: 'transparent',
}}
>
{/* Screens */}
</Drawer.Navigator>
);
}

drawerHideStatusBarOnOpen

当设置为 true 时,只要抽屉被拉出或处于 "open" 状态,抽屉就会隐藏操作系统状态栏。

¥When set to true, Drawer will hide the OS status bar whenever the drawer is pulled or when it's in an "open" state.

drawerStatusBarAnimation

隐藏状态栏时的动画。与 hideStatusBar 结合使用。

¥Animation of the statusbar when hiding it. use in combination with hideStatusBar.

支持的值:

¥Supported values:

  • slide

  • fade

  • none

仅 iOS 支持此功能。默认为 slide

¥This is only supported on iOS. Defaults to slide.

overlayColor

当抽屉打开时,颜色叠加显示在内容视图的顶部。当抽屉打开时,不透明度会从 0 动画到 1

¥Color overlay to be displayed on top of the content view when drawer gets open. The opacity is animated from 0 to 1 when the drawer opens.

sceneContainerStyle

封装屏幕内容的组件的样式对象。

¥Style object for the component wrapping the screen content.

gestureHandlerProps

传递给底层平移手势处理程序的属性。

¥Props to pass to the underlying pan gesture handler.

Web 上不支持此功能。

¥This is not supported on Web.

swipeEnabled

是否可以使用滑动手势打开或关闭抽屉。默认为 true

¥Whether you can use swipe gestures to open or close the drawer. Defaults to true.

Web 上不支持滑动手势。

¥Swipe gesture is not supported on Web.

swipeEdgeWidth

允许定义滑动手势应激活距内容视图边缘多远。

¥Allows for defining how far from the edge of the content view the swipe gesture should activate.

Web 上不支持此功能。

¥This is not supported on Web.

swipeMinDistance

应激活打开抽屉的最小滑动距离阈值。

¥Minimum swipe distance threshold that should activate opening the drawer.

keyboardDismissMode

当滑动手势开始时是否应关闭键盘。默认为 'on-drag'。设置为 'none' 以禁用键盘处理。

¥Whether the keyboard should be dismissed when the swipe gesture begins. Defaults to 'on-drag'. Set to 'none' to disable keyboard handling.

unmountOnBlur

当离开该屏幕时是否应卸载该屏幕。卸载屏幕会重置屏幕中的任何本地状态以及屏幕中嵌套导航器的状态。默认为 false

¥Whether this screen should be unmounted when navigating away from it. Unmounting a screen resets any local state in the screen as well as state of nested navigators in the screen. Defaults to false.

通常,我们不建议启用此属性,因为用户不希望在切换屏幕时丢失其导航历史记录。如果启用此属性,请考虑这是否真的能为用户提供更好的体验。

¥Normally, we don't recommend enabling this prop as users don't expect their navigation history to be lost when switching screens. If you enable this prop, please consider if this will actually provide a better experience for the user.

freezeOnBlur

布尔值,指示是否阻止非活动屏幕重新渲染。默认为 false。当 react-native-screens 包中的 enableFreeze() 在应用顶部运行时,默认为 true

¥Boolean indicating whether to prevent inactive screens from re-rendering. Defaults to false. Defaults to true when enableFreeze() from react-native-screens package is run at the top of the application.

需要 react-native-screens 版本 >=3.16.0。

¥Requires react-native-screens version >=3.16.0.

仅支持 iOS 和 Android。

¥Only supported on iOS and Android.

¥Header related options

你可以找到标题相关选项 此处 的列表。这些 options 可以在 Drawer.navigatorscreenOptions 属性或 Drawer.Screenoptions 属性下指定。你不必直接使用 @react-navigation/elements 来使用这些选项,它们只是记录在该页面中。

¥You can find the list of header related options here. These options can be specified under screenOptions prop of Drawer.navigator or options prop of Drawer.Screen. You don't have to be using @react-navigation/elements directly to use these options, they are just documented in that page.

除此之外,抽屉中还支持以下选项:

¥In addition to those, the following options are also supported in drawer:

使用自定义标头代替默认标头。

¥Custom header to use instead of the default header.

它接受一个返回 React 元素以显示为标题的函数。该函数接收一个包含以下属性的对象作为参数:

¥This accepts a function that returns a React Element to display as a header. The function receives an object containing the following properties as the argument:

  • navigation - 当前屏幕的导航对象。

    ¥navigation - The navigation object for the current screen.

  • route - 当前屏幕的路由对象。

    ¥route - The route object for the current screen.

  • options - 当前屏幕的选项

    ¥options - The options for the current screen

  • layout - 屏幕尺寸,包含 heightwidth 属性。

    ¥layout - Dimensions of the screen, contains height and width properties.

示例:

¥Example:

import { getHeaderTitle } from '@react-navigation/elements';

// ..

header: ({ navigation, route, options }) => {
const title = getHeaderTitle(options, route.name);

return <MyHeader title={title} style={options.headerStyle} />;
};

要为导航器中的所有屏幕设置自定义标题,你可以在导航器的 screenOptions 属性中指定此选项。

¥To set a custom header for all the screens in the navigator, you can specify this option in the screenOptions prop of the navigator.

headerStyle 中指定 height

¥Specify a height in headerStyle

如果你的自定义标题高度与默认标题高度不同,那么你可能会注意到由于测量异步而导致的故障。明确指定高度将避免此类故障。

¥If your custom header's height differs from the default header height, then you might notice glitches due to measurement being async. Explicitly specifying the height will avoid such glitches.

示例:

¥Example:

headerStyle: {
height: 80, // Specify the height of your custom header
};

请注意,默认情况下,此样式不会应用于标头,因为你可以控制自定义标头的样式。如果你也想将此样式应用于标题,请使用 props 中的 options.headerStyle

¥Note that this style is not applied to the header by default since you control the styling of your custom header. If you also want to apply this style to your header, use options.headerStyle from the props.

headerShown

是否显示或隐藏屏幕标题。默认情况下显示标题。将其设置为 false 会隐藏标题。

¥Whether to show or hide the header for the screen. The header is shown by default. Setting this to false hides the header.

活动

¥Events

导航器可以对某些操作进行 触发事件。支持的事件有:

¥The navigator can emit events on certain actions. Supported events are:

drawerItemPress

当用户按下抽屉中屏幕的按钮时会触发此事件。默认情况下,抽屉式物品压机会执行以下几项操作:

¥This event is fired when the user presses the button for the screen in the drawer. By default a drawer item press does several things:

  • 如果屏幕未聚焦,按下抽屉项目将使该屏幕聚焦

    ¥If the screen is not focused, drawer item press will focus that screen

  • 如果屏幕已经聚焦,那么它将关闭抽屉

    ¥If the screen is already focused, then it'll close the drawer

要防止默认行为,你可以调用 event.preventDefault

¥To prevent the default behavior, you can call event.preventDefault:

React.useEffect(() => {
const unsubscribe = navigation.addListener('drawerItemPress', (e) => {
// Prevent default behavior
e.preventDefault();

// Do something manually
// ...
});

return unsubscribe;
}, [navigation]);

如果你有自定义抽屉内容,请确保发出此事件。

¥If you have custom drawer content, make sure to emit this event.

帮手

¥Helpers

抽屉导航器向导航属性添加以下方法:

¥The drawer navigator adds the following methods to the navigation prop:

openDrawer

打开抽屉面板。

¥Opens the drawer pane.

navigation.openDrawer();

closeDrawer

关闭抽屉面板。

¥Closes the drawer pane.

navigation.closeDrawer();

toggleDrawer

如果抽屉窗格已关闭,则打开抽屉窗格;如果抽屉窗格已打开,则将其关闭。

¥Opens the drawer pane if closed, closes the drawer pane if opened.

navigation.toggleDrawer();

jumpTo

导航至抽屉式导航器中的现有屏幕。该方法接受以下参数:

¥Navigates to an existing screen in the drawer navigator. The method accepts the following arguments:

  • name - string - 要跳转到的路由名称。

    ¥name - string - Name of the route to jump to.

  • params - object - 屏幕参数传递到目标路由。

    ¥params - object - Screen params to pass to the destination route.

navigation.jumpTo('Profile', { owner: 'Satya' });

示例

¥Example

import { createDrawerNavigator } from '@react-navigation/drawer';

const Drawer = createDrawerNavigator();

function MyDrawer() {
return (
<Drawer.Navigator initialRouteName="Feed">
<Drawer.Screen
name="Feed"
component={Feed}
options={{ drawerLabel: 'Home' }}
/>
<Drawer.Screen
name="Notifications"
component={Notifications}
options={{ drawerLabel: 'Updates' }}
/>
<Drawer.Screen
name="Profile"
component={Profile}
options={{ drawerLabel: 'Profile' }}
/>
</Drawer.Navigator>
);
}

检查抽屉是否打开

¥Checking if the drawer is open

你可以使用 useDrawerStatus 钩子检查抽屉是否打开。

¥You can check if the drawer is open by using the useDrawerStatus hook.

import { useDrawerStatus } from '@react-navigation/drawer';

// ...

const isDrawerOpen = useDrawerStatus() === 'open';

如果你不能使用钩子,你也可以使用 getDrawerStatusFromState 助手:

¥If you can't use the hook, you can also use the getDrawerStatusFromState helper:

import { getDrawerStatusFromState } from '@react-navigation/drawer';

// ...

const isDrawerOpen = getDrawerStatusFromState(navigation.getState()) === 'open';

对于类组件,你可以监听 state 事件来检查抽屉是否打开或关闭:

¥For class components, you can listen to the state event to check if drawer was opened or closed:

class Profile extends React.Component {
componentDidMount() {
this._unsubscribe = navigation.addListener('state', () => {
const isDrawerOpen =
getDrawerStatusFromState(navigation.getState()) === 'open';

// do something
});
}

componentWillUnmount() {
this._unsubscribe();
}

render() {
// Content of the component
}
}

将抽屉导航器嵌套在其他导航器中

¥Nesting drawer navigators inside others

如果抽屉式导航器嵌套在提供某些 UI 的另一个导航器(例如选项卡导航器或堆栈导航器)内,则抽屉将在这些导航器的 UI 下方呈现。抽屉将出现在选项卡栏下方和堆栈标题下方。你需要将抽屉式导航器设为任何导航器的父级,其中抽屉式导航器应呈现在其 UI 之上。

¥If a drawer navigator is nested inside of another navigator that provides some UI, for example, a tab navigator or stack navigator, then the drawer will be rendered below the UI from those navigators. The drawer will appear below the tab bar and below the header of the stack. You will need to make the drawer navigator the parent of any navigator where the drawer should be rendered on top of its UI.