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

如何为React FullCalendar表格单元格按过去/未来时间设置动态底色?

React FullCalendar 单元格动态上色解决方案

核心思路

借助FullCalendar的dayCellClassNames或dayCellDidMount钩子,判断单元格日期与当前时间的关系,动态添加自定义CSS类,实现过去、当下、未来单元格的视觉区分。

具体实现步骤

1. 配置FullCalendar组件

在React组件中添加状态判断的回调函数,返回对应类名:

import FullCalendar from '@fullcalendar/react';
import dayGridPlugin from '@fullcalendar/daygrid';

const Calendar = () => {
  const getCellClassNames = ({ date }) => {
    const now = new Date();
    // 仅保留年月日,忽略时分秒避免误判
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const cellDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());

    if (cellDate < today) {
      return 'past-day';
    } else if (cellDate.getTime() === today.getTime()) {
      return 'today-day';
    }
    return 'future-day';
  };

  return (
    <FullCalendar
      plugins={[dayGridPlugin]}
      initialView="dayGridMonth"
      dayCellClassNames={getCellClassNames}
    />
  );
};

export default Calendar;

2. 编写CSS样式

定义对应类的视觉样式,匹配预期效果:

/* 过去日期单元格 */
.past-day {
  background-color: #e0e0e0;
  color: #666;
}

/* 当天日期单元格 */
.today-day {
  background-color: #ffeb3b;
  color: #333;
  font-weight: bold;
}

/* 未来日期单元格 */
.future-day {
  background-color: #c8e6c9;
  color: #2e7d32;
}

/* 覆盖默认样式避免冲突 */
.fc-daygrid-day-frame {
  height: 100%;
}
.fc-daygrid-day-top {
  padding: 4px;
}

3. 备选方案(若dayCellClassNames不生效)

使用dayCellDidMount钩子手动操作DOM添加类:

const dayCellDidMount = ({ el, date }) => {
  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const cellDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());

  if (cellDate < today) {
    el.classList.add('past-day');
  } else if (cellDate.getTime() === today.getTime()) {
    el.classList.add('today-day');
  } else {
    el.classList.add('future-day');
  }
};

将该函数传入FullCalendar组件的dayCellDidMount属性即可。

注意事项

  • 若使用时间类视图(如timeGridWeek),需调整判断逻辑,对比具体时间点而非仅年月日。
  • 确保CSS样式优先级高于FullCalendar默认样式,可通过添加父容器类名或使用!important(不推荐)解决样式覆盖问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 14:52:05