首页 > 解决方案 > React Native Hamburger onPress 问题

问题描述

我试图通过在标题的汉堡包上包含 onPress() 来导航抽屉,但它不适用于 navigation.toggleDrawer() 函数。

这是代码:

import * as React from 'react';
import { Button, View } from 'react-native';
import { createDrawerNavigator } from '@react-navigation/drawer';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { Ionicons } from '@expo/vector-icons';

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.navigate('Home')} title="Go back home" />
    </View>
  );
}

const Drawer = createDrawerNavigator();

function draw() {
  return (

      <Drawer.Navigator initialRouteName="Home" >
        <Drawer.Screen name="Home" component={HomeScreen} 
        options={{
        drawerIcon: () => <Ionicons name='md-home' size={30} color='#130f40' />,
          }}
         />
        <Drawer.Screen name="Notifications" component={NotificationsScreen}
        options={{
        drawerIcon: () => <Ionicons name='md-notifications' size={30} color='#130f40' />,
          }}
         />
      </Drawer.Navigator>

  );
}



const Stack = createStackNavigator();

function Def(){
  return (
    <NavigationContainer>
    <Stack.Navigator>
    <Stack.Screen
        name="Home"
        component={draw}
        options={{
          title: 'My home',
          headerStyle: {
            backgroundColor: '#5f27cd',
          },
          headerTintColor: '#fff',
          headerTitleStyle: {
            fontWeight: 'bold',
          },

          headerLeft: () =>  (<Ionicons name='md-menu' style={{paddingLeft: "20px"}} size={30} color='white' onPress={() => navigation.toggleDrawer()} />),


        }}

      />
    </Stack.Navigator>
    </NavigationContainer>    
  )
}

export default Def;

我在带有 onPress() 函数的 Ionicons 中添加了 navigation.toggleDrawer() 函数,但它不起作用。错误说导航没有定义。

标签: androidreactjsreact-nativenavigation

解决方案


尝试这个

 headerLeft: ({navigation}) =>  (<Ionicons name='md-menu' style={{paddingLeft: "20px"}} size={30} color='white' onPress={() => navigation.toggleDrawer()} />)

希望能帮助到你


推荐阅读