为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,同时传递otherprops以保留组件原有的布局和交互逻辑 - 日期比较使用
toDateString(),避免时间部分差异导致判断错误 - 通过
sx调整Badge的位置,避免遮挡日期内容
内容的提问来源于stack exchange,提问作者Dewa Samudra
相关产品推荐
相关产品推荐

