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

如何在react-calendar组件中高亮标记已占用的指定日期

react-calendar 占用日期高亮实现方案

使用组件内置的tileClassName属性即可为指定日期注入自定义高亮样式,无需额外修改组件源码,具体实现如下:

  • 修正原有代码的语法问题:原代码中new Date.toDateString()缺少实例化括号,正确写法为new Date().toDateString(),同时记得引入react-calendar的官方基础样式,否则日历会无默认排版。
  • 编写单元格类名判断函数:日历渲染每个日期单元格时会触发该函数,判断当前单元格日期是否属于需要标记的占用日期,命中则返回自定义高亮类名。
  • 编写高亮CSS样式:为标记的占用日期设置区别于普通日期的背景色、文字色等视觉样式。

完整代码示例

组件逻辑代码

import React, { useState} from 'react';
import Calendar from 'react-calendar';
// 引入组件官方基础样式
import 'react-calendar/dist/Calendar.css';
// 引入自定义高亮样式
import './calendar-mark.css';

export default function Test() {
  const [date, setDate] = useState(new Date().toDateString());
  // 每月重复标记的日期(数值类型,匹配每月的对应日)
  const occupiedDates = [3, 10, 20];

  // 日期单元格类名判断逻辑
  const setTileClass = ({ date, view }) => {
    // 仅在月视图下生效,年/年代视图不做标记
    if (view !== 'month') return null;
    const day = date.getDate();
    return occupiedDates.includes(day) ? 'occupied-highlight' : null;
  };

  return(
    <div>
      <p>当前选中日期:{date}</p>
      <Calendar 
        onChange={setDate} 
        value={date}
        tileClassName={setTileClass}
      />
    </div>
  );
}

自定义样式文件 calendar-mark.css

/* 占用日期高亮样式,可根据项目设计规范调整颜色、圆角等属性 */
.react-calendar__tile.occupied-highlight {
  background: #f53f3f;
  color: #fff;
  border-radius: 50%;
}
.react-calendar__tile.occupied-highlight:enabled:hover,
.react-calendar__tile.occupied-highlight:enabled:focus {
  background: #cb2634;
}

非每月重复的绝对日期标记方案

如果需要标记的是特定年月的具体日期(比如仅标记2024年10月3日、2024年11月10日这类非重复日期),调整日期存储格式和匹配逻辑即可:

// 存储为YYYY-MM-DD格式的绝对日期
const occupiedDates = ['2024-10-03', '2024-10-10', '2024-11-20'];

const setTileClass = ({ date, view }) => {
  if (view !== 'month') return null;
  // 把当前单元格日期格式化为YYYY-MM-DD做全等匹配
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const currentDateFormat = `${year}-${month}-${day}`;
  return occupiedDates.includes(currentDateFormat) ? 'occupied-highlight' : null;
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 03:36:16