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

MUI X Date Picker中无法显示带勾选图标的徽章问题求助

解决MUI X Date Picker高亮日期的CheckIcon徽章不显示问题

你的代码里有几个关键问题导致勾选图标无法正常显示,以下是修复方案:

问题分析

  1. renderInput 未返回组件:原代码中renderInput的回调函数用大括号包裹,但没有返回TextField组件,会导致组件内部渲染逻辑异常。
  2. Badge的badgeContent 传入undefined:当日期不在高亮列表中时,给badgeContent传undefined会干扰Badge的渲染逻辑,应该传入null明确表示不渲染徽章内容。
  3. 图标颜色与Badge背景冲突:默认Badge背景色为primary(蓝色),红色图标在蓝色背景下辨识度极低,建议调整Badge颜色配合图标显示。

修复后的代码

import { useState } from 'react';
import TextField from '@mui/material/TextField';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { StaticDatePicker } from '@mui/x-date-pickers/StaticDatePicker';
import Badge from '@mui/material/Badge';
import { PickersDay } from '@mui/x-date-pickers/PickersDay';
import CheckIcon from '@mui/icons-material/Check';

export const Calendar = () => {
  const [value, setValue] = useState(new Date());
  const [highlightedDays, setHighlightedDays] = useState([1, 2, 13]);

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns}>
      <StaticDatePicker
        variant='static'
        orientation='portrait'
        value={value}
        disableFuture
        onChange={(newValue) => setValue(newValue)}
        // 修复:正确返回TextField组件
        renderInput={(params) => <TextField {...params} />}
        renderDay={(day, _value, DayComponentProps) => {
          const isSelected =
            !DayComponentProps.outsideCurrentMonth &&
            highlightedDays.includes(day.getDate()); // 用includes替代indexOf更直观

          return (
            <Badge
              key={day.toString()}
              overlap='circular'
              color="success" // 调整Badge背景为绿色,搭配白色图标更清晰
              badgeContent={isSelected ? <CheckIcon color="white" /> : null} // 用null替代undefined
            >
              <PickersDay {...DayComponentProps} />
            </Badge>
          );
        }}
      />
    </LocalizationProvider>
  );
};

额外优化说明

  • 用Array.includes()替代indexOf()判断日期是否在高亮列表中,代码更易读。
  • 将CheckIcon颜色设为白色,搭配Badge的success绿色背景,图标显示更醒目。
  • 确保renderInput正确返回组件,避免组件内部状态异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:13:18