ドロワーナビゲーション
ナビゲーションの一般的なパターンとしては、画面間を移動するために左(または右)側からドロワーを使用することです。
続行する前に、@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';