You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中如何在函数内调用drawer navigator实现点击图片开侧边栏

你写的代码存在几个核心错误:

  • 抽屉导航的配置不能写在点击事件回调里,React Navigation的路由结构必须提前定义在组件渲染层级中,onPress回调执行的是逻辑操作,返回的JSX不会被渲染到页面上。
  • 你重复绑定了onPress事件,Image组件本身没有onPress属性,外层已经套了TouchableWithoutFeedback,只需要在外层组件绑定事件即可。
  • 抽屉导航需要在根层级统一定义,不能嵌套在TopBar组件内部。

正确实现流程

第一步:根组件定义抽屉导航结构

先在应用的入口根组件配置完整的抽屉路由,把主页面和侧边栏组件都注册进去:

import { createDrawerNavigator } from '@react-navigation/drawer';
import { NavigationContainer } from '@react-navigation/native';
// 引入你的主页面、侧边栏组件
import MainScreen from './screens/MainScreen';
import SideBar from './components/SideBar';

const Drawer = createDrawerNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Drawer.Navigator 
        // 自定义侧边栏内容为你写的SideBar组件
        drawerContent={(props) => <SideBar {...props} />}
      >
        <Drawer.Screen 
          name="Main" 
          component={MainScreen}
          // 隐藏默认导航头,使用你自定义的TopBar
          options={{ headerShown: false }}
        />
      </Drawer.Navigator>
    </NavigationContainer>
  );
}

第二步:修改TopBar组件实现点击打开抽屉

用React Navigation提供的useNavigation钩子获取导航实例,直接调用内置的openDrawer方法即可:

import { View, TouchableWithoutFeedback, Image } from 'react-native';
import { useNavigation } from '@react-navigation/native';

function TopBar(props) {
  const navigation = useNavigation();

  const sideMenuHandler = () => {
    // 调用内置方法打开抽屉
    navigation.openDrawer();
    // 如果需要切换抽屉开关状态可以用 navigation.toggleDrawer()
    // 关闭抽屉用 navigation.closeDrawer()
  };

  return (
    <View>
      <TouchableWithoutFeedback onPress={sideMenuHandler}>
        <Image source={require('../assets/profile.jpg')} />
      </TouchableWithoutFeedback>
    </View>
  );
}

export default TopBar;

注意事项

  • 确保你已经完整安装了抽屉导航的所有依赖:react-native-gesture-handler、react-native-reanimated,并且按照要求配置了babel插件,否则抽屉交互会失效。
  • 所有嵌套在Drawer.Navigator下的页面组件,都可以通过useNavigation钩子拿到抽屉操作方法。

内容的提问来源于stack exchange,提问作者Zenixo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 19:15:05