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

React中antd Calendar使用cellRender出现日期重复等问题求助

问题解决方案

1. 取消默认选中的日期

Antd Calendar组件默认会绑定当前日期为选中状态,只需给每个Calendar组件**显式设置value={null}**即可取消默认选中。如果需要维护自定义选中状态,可初始化一个状态变量为null,再绑定到value属性上。

2. 避免日期重复显示

日期重复是因为自定义cellRender时重复渲染了日期文本,正确做法是保留组件原生的日期节点。cellRender的参数info中包含originNode,这是组件原本的日期元素,直接复用它即可避免重复:

const cellRender = (value, info) => {
  const day = value.getDay();
  // 匹配周三(3)、周四(4)
  const isHighlight = day === 3 || day === 4;
  return (
    <div className={isHighlight ? 'highlight-cell' : ''}>
      {info.originNode}
    </div>
  );
};

3. 保持日期可选中同时保留高亮功能

之前日期无法选中是因为自定义元素覆盖了原生交互区域,复用originNode后会保留原生的点击选中逻辑。如果要实现多日历独立选中,需给每个Calendar分配独立的状态管理:

const [selectedDates, setSelectedDates] = useState({});

const handleSelect = (date, monthKey) => {
  setSelectedDates(prev => ({
    ...prev,
    [monthKey]: date
  }));
};

// 渲染12个月份日历
{Array.from({ length: 12 }).map((_, index) => {
  const month = index + 1;
  return (
    <Calendar
      key={month}
      value={selectedDates[month] || null}
      onSelect={(date) => handleSelect(date, month)}
      cellRender={cellRender}
      defaultValue={new Date(new Date().getFullYear(), month - 1, 1)}
      mode="month"
    />
  );
})}

完整核心代码示例

import { useState } from 'react';
import { Calendar } from 'antd';
import './CalendarList.css';

const CalendarList = () => {
  const [selectedDates, setSelectedDates] = useState({});

  const cellRender = (value, info) => {
    const day = value.getDay();
    const isHighlight = day === 3 || day === 4;
    return (
      <div className={`calendar-cell ${isHighlight ? 'highlight' : ''}`}>
        {info.originNode}
      </div>
    );
  };

  const handleSelect = (date, monthKey) => {
    setSelectedDates(prev => ({
      ...prev,
      [monthKey]: date
    }));
  };

  return (
    <div className="calendar-list">
      {Array.from({ length: 12 }).map((_, index) => {
        const month = index + 1;
        const year = new Date().getFullYear();
        return (
          <div key={month} className="calendar-item">
            <Calendar
              value={selectedDates[month] || null}
              onSelect={(date) => handleSelect(date, month)}
              cellRender={cellRender}
              defaultValue={new Date(year, month - 1, 1)}
              mode="month"
            />
          </div>
        );
      })}
    </div>
  );
};

export default CalendarList;

配套CSS:

.calendar-list {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  padding: 20px;
}

.calendar-cell.highlight {
  background-color: #e6ffed;
  border-radius: 4px;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 16:25:54