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

为何navigation.closeDrawer不是函数?react-navigation v2.x问题求助

解决react-navigation 2.x中抽屉导航closeDrawer调用报错的问题

我来帮你排查这个问题~先看你代码里的关键错误:你误用了navigation.actions.closeDrawer(),这不是正确的调用方式!

问题原因分析

在你使用的react-navigation 2.x版本中:

  • closeDrawer是navigation对象的直接方法,可以直接通过this.props.navigation.closeDrawer()调用,完全不需要加.actions前缀。
  • 你提到的actions(准确说是NavigationActions)是用来创建action对象的工具,要是想用这种方式触发关闭,得配合dispatch,比如this.props.navigation.dispatch(NavigationActions.closeDrawer()),但显然直接调用封装好的closeDrawer()更简便。

你说console.log能看到navigation下有closeDrawer方法,但实际调用时找错了路径——navigation对象里根本没有你想的actions属性,自然会报“Cannot read property 'closeDrawer' of undefined”的错误。

修正后的DrawerPanel代码

把按钮的onPress逻辑改成下面这样,就能正常关闭抽屉并跳转了:

import React, { Component } from 'react';
import { ScrollView, Text } from 'react-native';
import { View } from 'react-native-animatable';
import { List, Button } from 'react-native-elements';

class DrawerPanel extends Component {
  render() {
    console.log(this.props);
    return (
      <ScrollView style={{ backgroundColor: '#81A3A7' }}>
        <Button
          onPress={() => {
            // 直接调用closeDrawer方法
            this.props.navigation.closeDrawer();
            this.props.navigation.navigate('MainActivity');
          }}
          backgroundColor={'#81A3A7'}
          containerViewStyle={{ width: '100%', marginLeft: -61 }}
          title='Main page'
        />
        <Button
          onPress={() => {
            // 这里也建议加上关闭抽屉的逻辑,提升用户体验
            this.props.navigation.closeDrawer();
            this.props.navigation.navigate('ThisWeek');
          }}
          backgroundColor={'#81A3A7'}
          containerViewStyle={{ width: '100%', marginLeft: -46 }}
          title='This week'
        />
      </ScrollView>
    );
  }
}

export default DrawerPanel;

额外提示

第二个按钮点击后抽屉不会自动关闭,建议也加上closeDrawer()调用,这样用户操作完抽屉后页面会更流畅~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:06:32