为 MUI 日期选择器创建自定义日历标题时如何使用 date-fns 而不是 dayjs

问题描述 投票:0回答:1

我正在尝试为 MUI 日期选择器组件添加自定义日历标头,但在将默认 dayjs 类型更改为 date-fns 时遇到了麻烦。

这是我的日期选择器组件和自定义标题组件。

<StyledDatePicker
            open={open}
            value={date}
            onChange={(newValue) => onChange(newValue as Date)}
            slots={{
              openPickerIcon: CalendarIcon,
              shortcuts: CustomRangeShortcuts as any,
              calendarHeader: CustomCalendarHeader,
            }}
            slotProps={{
              actionBar: {
                actions: ['today'],
              },
              shortcuts: {
                items: MUI_DATE_PICKER_SHORTCUTS,
              },
              openPickerButton: {
                onClick: iconButtonOnClick,
              },
              textField: { variant: 'filled', onFocus: inputFocused, onBlur: close },
            }}
          />
const CustomCalendarHeader = (props: PickersCalendarHeaderProps<Date>) => {
  const { currentMonth, onMonthChange } = props;

  const selectNextMonth = () => onMonthChange(currentMonth.add(1, 'month'), 'left');
  const selectNextYear = () => onMonthChange(currentMonth.add(1, 'year'), 'left');
  const selectPreviousMonth = () => onMonthChange(currentMonth.subtract(1, 'month'), 'right');
  const selectPreviousYear = () => onMonthChange(currentMonth.subtract(1, 'year'), 'right');

  return (
    <CustomCalendarHeaderRoot>
      <Stack spacing={1} direction="row">
        <IconButton onClick={selectPreviousYear} title="Previous year">
          <KeyboardDoubleArrowLeftIcon />
        </IconButton>
        <IconButton onClick={selectPreviousMonth} title="Previous month">
          <ChevronLeft />
        </IconButton>
      </Stack>
      <Typography variant="body2">{currentMonth.format('MMMM YYYY')}</Typography>
      <Stack spacing={1} direction="row">
        <IconButton onClick={selectNextMonth} title="Next month">
          <ChevronRight />
        </IconButton>
        <IconButton onClick={selectNextYear} title="Next year">
          <KeyboardDoubleArrowRightIcon />
        </IconButton>
      </Stack>
    </CustomCalendarHeaderRoot>
  );
}

示例中的自定义 header prop 类型使用 Dayjs (

PickersCalendarHeaderProps<Dayjs>
),但我想使用 date-fns,如何使用 date-fns 而不是 dayjs 来实现?

javascript reactjs material-ui date-fns mui-x-date-picker
1个回答
0
投票

date-fns
提供与
day.js
类似的功能。检查以下代码:👇

import { addMonths, addYears, subMonths, subYears } from 'date-fns';

const selectNextMonth = () => onMonthChange(addMonths(currentMonth, 1), 'left');
const selectNextYear = () => onMonthChange(addYears(currentMonth, 1), 'left');
const selectPreviousMonth = () => onMonthChange(subMonths(currentMonth, 1), 'right');
const selectPreviousYear = () => onMonthChange(subYears(currentMonth, 1), 'right');

这些更改的效果与您对

day.js
所做的操作相同。

© www.soinside.com 2019 - 2024. All rights reserved.