javascript - 使用 @material-ui/pickers DatePicker 显示并允许选择月外的日期
问题描述
我目前正在开发一个 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 选择器方面没有太多深入的经验,任何人都可以就是否有可能实现所需的功能提出建议?如果是,如何最好地做到这一点?
解决方案
我遇到了这个确切的问题,我们需要做的是覆盖点击自定义日期,使用 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}
/>
推荐阅读
- javascript - 在 iframe 中下载 PDF 内容,源 url 没有 .pdf 扩展名
- package - UIOP 无法识别本地昵称关键字
- r - 点大小如何与转换后的值相关,但图例保留原始值?
- laravel - 尝试安装 composer League/flysystem-aws-s3-v3 时出现错误
- javascript - 如何呈现搜索结果列表?
- python - 遍历循环时未出现所有元素
- python - 除了不使用查找错误python
- git - 如何让git中的不同分支指向同一个子模块的不同分支
- python - 如果断言通过,是否评估 Python 断言消息
- java - 有效读取文本文件