抽屉导航
导航中的常见模式是使用左侧(有时是右侧)的抽屉在屏幕之间导航。
在继续之前,请先安装并配置 @react-navigation/drawer
及其依赖项,方法是按照 安装说明 进行操作。
基于抽屉的导航的最小示例
要使用此抽屉导航器,请从 @react-navigation/drawer
中导入它:(向右滑动以打开)
import * as React from 'react';
import { Button, View } from 'react-native';
import { createDrawerNavigator } from '@react-navigation/drawer';
import { NavigationContainer } from '@react-navigation/native';
function HomeScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button
onPress={() => navigation.navigate('Notifications')}
title="Go to notifications"
/>
</View>
);
}
function NotificationsScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button onPress={() => navigation.goBack()} title="Go back home" />
</View>
);
}
const Drawer = createDrawerNavigator();
export default function App() {
return (
<NavigationContainer>
<Drawer.Navigator initialRouteName="Home">
<Drawer.Screen name="Home" component={HomeScreen} />
<Drawer.Screen name="Notifications" component={NotificationsScreen} />
</Drawer.Navigator>
</NavigationContainer>
);
}
打开和关闭抽屉
要打开和关闭抽屉,请使用以下帮助程序
navigation.openDrawer();
navigation.closeDrawer();
如果您想切换抽屉,请调用以下内容
navigation.toggleDrawer();
这些函数在幕后实际上只是在分发操作。
navigation.dispatch(DrawerActions.openDrawer());
navigation.dispatch(DrawerActions.closeDrawer());
navigation.dispatch(DrawerActions.toggleDrawer());
如果你想确定抽屉是打开还是关闭,你可以执行以下操作。
import { useDrawerStatus } from '@react-navigation/drawer';
// ...
const isDrawerOpen = useDrawerStatus() === 'open';