我目前正在研究一个React项目,该项目的主要目的是利用@ material-ui / pickers中的DatePicker。
正如标题所述,其中一项要求是还显示当前月份以外的日期,以及-如果未禁用这些日期,则允许用户选择这些日期,因此不必首先点击更改月份,然后选择日期。
到目前为止,我可以看到的唯一一种允许显示当前月份以外日期的方法是为我自己的renderDay函数提供自定义样式。
const styles = createStyles(theme => ({
dayDisabled: {
color: "rgba(255, 255, 255, 0.5)",
pointerEvents: "none"
},
nonCurrentMonthDay: {
color: theme.palette.text.disabled,
},
highlightNonCurrentMonthDay: {
color: '#676767',
},
highlight: {
background: theme.palette.primary.main,
color: theme.palette.common.black,
'&:hover':{
background: theme.palette.primary.main,
}
}
}));
renderWrappedWeekDay = (date, selectedDate, dayInCurrentMonth) => {
const { classes } = this.props;
const isSelectedDay = isSameDay(date, selectedDate);
const dayClassName = clsx(classes.day, {
[classes.nonCurrentMonthDay]: !dayInCurrentMonth,
[classes.highlightNonCurrentMonthDay]: !dayInCurrentMonth,
[classes.highlight]: isSelectedDay,
[classes.dayDisabled]: el.props.disabled
});
return (
<IconButton className={dayClassName}>
<span> {format(date, "d")} </span>
</IconButton>
);
};
但是当单击当前月份日期之外的任何日期时,我无法识别出触发onChange事件的任何方式。
由于我对材料UI选取器没有太多的深入经验,因此有人能建议是否可以实现所需的功能吗?如果是的话,如何最好地做到这一点?
答案 0 :(得分:1)
我遇到了这个确切的问题,我们需要做的是覆盖自定义日期的点击,使用 React.useState 更改所选日期,如下所示:
const [selectedDate, handleDateChange] = useState(moment());
renderWrappedWeekDay = (date, _ , dayInCurrentMonth) => {
const { classes } = this.props;
const isSelectedDay = isSameDay(date, selectedDate);
const dayClassName = clsx(classes.day, {
[classes.nonCurrentMonthDay]: !dayInCurrentMonth,
[classes.highlightNonCurrentMonthDay]: !dayInCurrentMonth,
[classes.highlight]: isSelectedDay,
[classes.dayDisabled]: el.props.disabled
});
return (
<IconButton className={dayClassName} onClick={(e) => {
e.stopPropagation() // stop the propagation
if (dayIsBetween) // use your own logic to limit selectable days
handleDateChange(date) // now, set state of the new selected date
}}
>
<span> {format(date, "d")} </span>
</IconButton>
);
};
日期选择器的值应该是状态,在本例中为 selectedDate
<DatePicker
variant="static"
labelFunc={date => (date ? date.format("YYYY/MM/DD") : "")}
value={selectedDate}
renderDay={renderWrappedWeekDay}
onChange={(e) => { }} // you need to override onChange otherwise you might see onChange not defined error
minDate={today}
maxDate={endDate}
/>