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

如何在react-calendar中仅选中当前月份时禁用上月导航箭头?

实现react-calendar选中当月时禁用上月导航箭头

可以通过自定义导航组件结合日期对比来实现这个需求,具体步骤如下:

  1. 维护状态跟踪当前选中的日期,同时计算当前月份和选中月份的起始日期(用于判断是否为同一月份)
  2. 自定义导航组件,根据日期对比结果决定是否禁用上月按钮
  3. 将自定义导航组件传入react-calendar的navigationComponent属性

代码示例

import Calendar from 'react-calendar';
import 'react-calendar/dist/Calendar.css';
import { useState } from 'react';

function MyCalendar() {
  const [selectedDate, setSelectedDate] = useState(new Date());

  // 获取当前月份的第一天(用于月份对比)
  const currentMonthStart = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
  // 获取选中日期所在月份的第一天
  const selectedMonthStart = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), 1);

  // 自定义导航组件
  const CustomNavigation = ({ prevButtonLabel, nextButtonLabel, onPrevClick, onNextClick }) => {
    // 判断是否要禁用上月按钮:选中月份等于当前月份时禁用
    const disablePrevBtn = selectedMonthStart.getTime() === currentMonthStart.getTime();

    return (
      <div className="react-calendar__navigation">
        <button
          onClick={onPrevClick}
          disabled={disablePrevBtn}
          className="react-calendar__navigation__prev-button"
        >
          {prevButtonLabel}
        </button>
        <span className="react-calendar__navigation__label">
          {selectedDate.toLocaleString('default', { month: 'long', year: 'numeric' })}
        </span>
        <button
          onClick={onNextClick}
          className="react-calendar__navigation__next-button"
        >
          {nextButtonLabel}
        </button>
      </div>
    );
  };

  return (
    <Calendar
      value={selectedDate}
      onChange={setSelectedDate}
      navigationComponent={CustomNavigation}
    />
  );
}

export default MyCalendar;

关键说明

  • 对比两个月份的起始日期(而非直接对比月份数字),避免跨年时的判断错误(比如12月和次年1月)
  • 自定义导航组件使用react-calendar默认的类名,保证样式和原生组件一致
  • 当选中月份切换为非当前月份时,上月按钮会自动恢复可点击状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 03:52:17