【问题标题】:Is it possible to prevent the Material UI DatePicker from selecting a day in calendar view?是否可以防止 Material UI DatePicker 在日历视图中选择一天?
【发布时间】:2020-07-16 04:34:13
【问题描述】:

我知道您可以将值设置为 null 以清除日期选择器,但日历视图(在我的情况下,设置为变体:“静态”)仍将日期设置为今天。

这个:

<DatePicker value={null} variant="static"/> 

..显示选择的当前日期,但我只想选择当前月份,当前日期。

这将有效地模仿 Google 日期选择器的行为,这是我正在尝试做的。 ([在 Google 中搜索] > 工具 > 任何时间.. > 自定义范围..)

【问题讨论】:

    标签: datepicker calendar material-ui


    【解决方案1】:

    最后,通过包装 DatePicker 并覆盖 renderDay 方法,我大致完成了我想做的事情。那里可能有更好的解决方案(我仍然只学习 Web 开发),如果有人知道,我很感兴趣,但这是我的 hacky 解决方案:

    import clsx from 'clsx';
    import format from 'date-fns/format';
    import { isSameDay, isBefore, isAfter } from 'date-fns';
    import React from 'react';
    import { DatePicker as MuiDatePicker } from '@material-ui/pickers';
    import { createStyles } from '@material-ui/core/styles';
    import { IconButton, withStyles } from '@material-ui/core';
    
    const styles = createStyles((theme) => ({
      dayWrapper: {
        position: 'relative',
      },
      day: {
        width: 36,
        height: 36,
        fontSize: theme.typography.caption.fontSize,
        margin: '0 2px',
        color: 'inherit',
      },
      nonCurrentMonthDay: {
        color: theme.palette.text.disabled,
      },
      highlightNonCurrentMonthDay: {
        color: '#676767',
      },
      highlight: {
        background: theme.palette.primary.main,
        color: theme.palette.common.white,
        borderRadius: '50%',
      },
    }));
    
    const DatePicker = (props) => {
      const { minDate, maxDate, value, classes } = props;
    
      const renderDay = (date, selectedDate, dayInCurrentMonth) => {
        const isSame = isSameDay(date, selectedDate);
        const beforeMin = isBefore(date, new Date(minDate));
        const afterMax = isAfter(date, new Date(maxDate));
        const emptyValue = value === null || value === '';
    
        const wrapperClassName = clsx({
          [classes.highlight]: isSame && !emptyValue,
        });
    
        const dayClassName = clsx(classes.day, {
          [classes.nonCurrentMonthDay]: !dayInCurrentMonth || beforeMin || afterMax,
          [classes.highlightNonCurrentMonthDay]: !dayInCurrentMonth,
        });
        return (
          <div className={wrapperClassName}>
            <IconButton className={dayClassName}>
              <span> {format(date, 'd')} </span>
            </IconButton>
          </div>
        );
      };
    
      return <MuiDatePicker renderDay={renderDay} {...props} />;
    };
    
    export default withStyles(styles)(DatePicker);
    

    【讨论】:

      【解决方案2】:

      这是一个老问题,但您可以使用 views 属性来阻止用户在日历中显示日期选择器。

      https://material-ui-pickers.dev/api/DatePicker

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-08-10
        • 2014-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多