下面是一个使用 @react-navigation/drawer
创建抽屉导航(Drawer Navigation)页面的完整示例。我们将通过 @react-navigation/native
和 @react-navigation/drawer
来实现一个简单的抽屉导航页面。
1. 安装依赖
在项目中安装必要的依赖:
npm install @react-navigation/native @react-navigation/drawer react-native-gesture-handler react-native-reanimated react-native-screens react-native-safe-area-context react-native-vector-icons
注意:
- 确保
react-native-gesture-handler
已正确安装并初始化。 - 在
babel.config.js
中添加react-native-reanimated/plugin
插件。
2. 初始化配置
在项目的入口文件(如 index.js
或 App.js
)中导入并初始化手势处理器:
import 'react-native-gesture-handler';
3. 示例代码
以下是一个完整的抽屉导航页面示例:
import React from 'react';
import { Button, View, Text, StyleSheet } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createDrawerNavigator } from '@react-navigation/drawer';
// 屏幕组件 1
function HomeScreen({ navigation }) {
return (
<View style={styles.container}>
<Text>Home Screen</Text>
<Button
title="Go to Details"
onPress={() => navigation.navigate('Details')}
/>
<Button
title="Open Drawer"
onPress={() => navigation.openDrawer()}
/>
</View>
);
}
// 屏幕组件 2
function DetailsScreen() {
return (
<View style={styles.container}>
<Text>Details Screen</Text>
</View>
);
}
// 创建抽屉导航器
const Drawer = createDrawerNavigator();
export default function App() {
return (
<NavigationContainer>
<Drawer.Navigator
initialRouteName="Home" // 设置初始路由
screenOptions={{
drawerStyle: {
backgroundColor: '#c6cbef', // 抽屉背景颜色
width: 240, // 抽屉宽度
},
drawerActiveTintColor: '#fff', // 激活状态文字颜色
drawerInactiveTintColor: '#333', // 非激活状态文字颜色
}}
>
<Drawer.Screen
name="Home"
component={HomeScreen}
options={{ title: '主页' }} // 自定义标题
/>
<Drawer.Screen
name="Details"
component={DetailsScreen}
options={{ title: '详情页' }}
/>
</Drawer.Navigator>
</NavigationContainer>
);
}
// 样式
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
4. 添加自定义抽屉内容
可以通过 drawerContent
属性自定义抽屉的内容。例如:
<Drawer.Navigator
drawerContent={(props) => {
return (
<View style={{ flex: 1, paddingTop: 50 }}>
<Text style={{ fontSize: 20, padding: 20 }}>Custom Drawer Content</Text>
<Button title="Close Drawer" onPress={() => props.navigation.closeDrawer()} />
</View>
);
}}
>
{/* Screens */}
</Drawer.Navigator>
5. 添加图标
结合 react-native-vector-icons
,为抽屉菜单项添加图标:
import Icon from 'react-native-vector-icons/Ionicons';
<Drawer.Screen
name="Home"
component={HomeScreen}
options={{
title: '主页',
drawerIcon: ({ focused, color, size }) => (
<Icon name="home" size={size} color={color} />
),
}}
/>