You need to enable JavaScript to run this app. MUI Date Picker如何禁用10月除指定日期外的所有日期?
优惠活动
大模型
产品
解决方案
定价
更多

MUI Date Picker如何禁用10月除指定日期外的所有日期?

实现思路

shouldDisableDate是回调类型属性,接收日历组件当前遍历到的日期作为入参,返回布尔值:返回true代表该日期禁用,返回false代表该日期可选。你原有代码中的disableDates没有接收日期参数,也没有对应判断逻辑,因此无法生效。

具体逻辑设计:

  • 定义允许可选的10月日期号数组:[4,5,6,7,8,9,10,18]
  • 对传入的日期做校验:如果是2021年10月的日期,判断日期号是否在允许列表内,不在则返回true禁用
  • 非2021年10月的日期全部禁用,避免超出需求范围的可选日期
  • 额外修正原有代码中format属性的错误,原写法MM/MM/YYYY会重复展示月份,改为MM/DD/YYYY符合月/日/年的展示要求
完整可运行代码
import React, { useState } from 'react'
import DateMomentUtils from '@date-io/moment'
import { KeyboardDatePicker, MuiPickersUtilsProvider } from '@material-ui/pickers'
import { Controller, useFormContext } from 'react-hook-form'

const startDate = new Date('October 4, 2021 12:00:00')
const endDate = new Date('October 18, 2021 12:00:00')

// 修正后的禁用日期判断函数
const disableDates = (date) => {
  const allowedDays = [4,5,6,7,8,9,10,18]
  // 入参date为moment类型,使用moment提供的API取值
  if (date.year() === 2021 && date.month() === 9) { // month取值为0-11,10月对应值为9
    // 不在允许日期列表内则返回true(禁用)
    return !allowedDays.includes(date.date())
  }
  // 其他月份全部禁用
  return true
}

const CalendarInput = () => {
  const { control } = useFormContext()
  const [selectedDate, handleDateChange] = useState(new Date())
  
  return (
    <MuiPickersUtilsProvider utils={DateMomentUtils}>
      <Controller
        name='MUIPicker'
        control={control}
        render={({ field: { ref, ...rest } }) => (
          <KeyboardDatePicker
            variant='static'
            orientation='landscape'
            id='date-picker-dialog'
            label='Pick a date'
            format='MM/DD/YYYY'
            KeyboardButtonProps={{
              'aria-label': 'change date'
            }}
            value={selectedDate}
            onChange={handleDateChange}
            shouldDisableDate={disableDates}
            maxDate={endDate}
            minDate={startDate}
            {...rest}
          />
        )}
      />
    </MuiPickersUtilsProvider>
  )
}

内容的提问来源于stack exchange,提问作者aadlc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 10:51:00