You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Material UI日期范围选择器:仅允许选择禁止手动修改

禁止Material UI日期范围选择器手动输入,仅允许选择器选日期

要实现「只能通过选择器选日期,不能手动输入」的效果,核心是区分组件层级的只读设置:

  • 不要给DateRangePicker加readOnly:这个属性会直接禁用整个组件的交互(包括打开日期选择器),完全不符合需求。
  • 给内部TextField设置只读:通过InputProps的readOnly: true禁止手动输入,但依然允许点击输入框唤起选择器。

修改后的代码如下:

import { DateRangePicker, LocalizationProvider } from "@mui/x-date-pickers-pro";

// ...

<DateRangePicker
  // 移除或设为false:DateRangePicker的readOnly会禁用选择器
  // readOnly={readOnly}
  value={props.value ?? [new Date(), new Date()]}
  onChange={(newValue) => props.handleChange(newValue)}
  renderInput={(startProps, endProps) => (
    <div className={styles.inputGroup}>
      <div className={styles.fieldBox}>
        <TextField
          {...startProps}
          helperText={props.error?.message ?? props.error[0]?.message}
          label=""
          className={`textfield ${styles.borderLeftRadius}`}
          placeholder={startPlaceholder}
          error={!!(props.error?.message || props.error[1])}
          name={startDateName}
          InputProps={{
            // 这里设置只读,禁止手动输入
            readOnly: true,
            // 可选:添加光标样式提示可点击
            style: { cursor: 'pointer' }
          }}
        />
        <span className={styles.iconBox}>
          <FontAwesomeIcon icon={faCalendarWeek} size="1x" />
        </span>
      </div>
      <div className={styles.date_divider}>
        <FontAwesomeIcon icon={faArrowRight} size="xs" />
      </div>
      <div className={styles.fieldBox}>
        <TextField
          {...endProps}
          label=""
          error={!!(props.error?.message || props.error[1])}
          helperText={props.error?.message ?? props.error[1]?.message}
          className={`textfield ${styles.borderRightRadius}`}
          placeholder={endPlaceholder}
          name={endDateName}
          InputProps={{
            readOnly: true,
            style: { cursor: 'pointer' }
          }}
        />
        <span className={styles.iconBox}>
          <FontAwesomeIcon icon={faCalendarWeek} size="1x" />
        </span>
      </div>
    </div>
  )}
/>

关键说明:

  • 移除DateRangePicker的readOnly后,用户可以正常点击输入框唤起日期选择器
  • TextField的readOnly: true会阻止用户手动输入或修改内容,但不影响点击事件触发选择器
  • 可选的cursor: 'pointer'样式可以让用户更直观地知道输入框是可点击的

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 14:12:06