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

为DateCalendar添加徽章:添加slotProps/slots后弹窗内容空白求助

解决Material UI DateCalendar徽章添加后弹窗空白问题

问题原因

弹窗空白通常是因为slotProps配置错误,比如错误覆盖了日期单元格的默认渲染逻辑,导致组件无法生成有效JSX。

正确实现方式

通过slotProps.day自定义日期单元格渲染,在保留原有日期显示的基础上添加徽章,完整代码如下:

import { Badge } from '@mui/material';
// 定义需要显示徽章的日期数组(根据实际业务调整)
const badgedDates = [new Date(2024, 4, 15), new Date(2024, 4, 20)];

<Dialog open={openModal} onClose={handleModalClose}>
  <DialogTitle>
    {selectedData && `${selectedData.firstName} ${selectedData.lastName}'s Calendar`}
  </DialogTitle>
  <DialogContent>
    <DateCalendar
      readOnly
      views={["day"]}
      disableFuture
      sx={{ width: "max-content" }}
      renderLoading={() => <DayCalendarSkeleton />}
      value={value}
      onChange={(newValue) => setValue(newValue)}
      slotProps={{
        day: ({ day, ...other }) => {
          // 判断当前日期是否需要显示徽章
          const hasBadge = badgedDates.some(date => 
            day.date.toDateString() === date.toDateString()
          );
          return (
            <div {...other}>
              {day.day}
              {hasBadge && (
                <Badge 
                  badgeContent="!" 
                  color="error" 
                  sx={{ position: 'absolute', top: 2, right: 2 }}
                />
              )}
            </div>
          );
        }
      }}
    />
  </DialogContent>
  <DialogActions>
    <Button onClick={handleModalClose} color="primary">
      Close
    </Button>
  </DialogActions>
</Dialog>

关键注意点

  • 必须在slotProps.day的渲染函数中返回有效JSX,同时传递other props以保留组件原有的布局和交互逻辑
  • 日期比较使用toDateString(),避免时间部分差异导致判断错误
  • 通过sx调整Badge的位置,避免遮挡日期内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 01:03:25