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

MUI MobileDateTimePicker:实现键盘输入与图标触发选择器弹窗

解决MUI MobileDateTimePicker点击TextField自动弹窗的问题

要实现点击TextField可手动输入、仅点击右侧图标打开选择器的需求,你需要手动控制选择器的打开状态,并禁用TextField默认的触发弹窗行为,具体实现如下:

  1. 新增状态管理选择器的打开/关闭
  2. 覆盖TextField的默认事件,阻止获焦/点击时打开弹窗
  3. 绑定图标点击事件来触发弹窗

修改后的代码:

import { useState } from 'react';
import IconButton from '@mui/material/IconButton';
import CalendarClockIcon from '@mui/icons-material/CalendarClock';

// ... 你的其他代码

<Controller
  name="start"
  control={control}
  render={({ field }) => {
    const [open, setOpen] = useState(false);

    const handleIconClick = () => {
      setOpen(true);
    };

    const handleTextFieldFocus = (e) => {
      e.stopPropagation();
    };

    const handleTextFieldClick = (e) => {
      if (e.target.tagName !== 'BUTTON') {
        e.stopPropagation();
      }
    };

    return (
      <MobileDateTimePicker
        {...field}
        value={new Date(field.value)}
        onChange={(newValue) => {
          if (newValue) {
            field.onChange(fTimestamp(newValue));
          }
        }}
        label="Začetek"
        format="dd/MM/yyyy HH:mm"
        ampm={false}
        open={open}
        onOpen={() => setOpen(true)}
        onClose={() => setOpen(false)}
        slotProps={{
          textField: {
            fullWidth: true,
            onFocus: handleTextFieldFocus,
            onClick: handleTextFieldClick,
            InputProps: {
              endAdornment: (
                <IconButton onClick={handleIconClick} edge="end">
                  <CalendarClockIcon />
                </IconButton>
              ),
            },
          },
        }}
      />
    );
  }}
/>

关键说明:

  • 用useState管理open状态,完全控制选择器的显示/隐藏
  • handleTextFieldFocus和handleTextFieldClick阻止了TextField输入区域的点击/获焦事件触发弹窗
  • 自定义InputProps.endAdornment替换默认图标,绑定点击事件来打开选择器
  • 保留了react-hook-form的Controller逻辑,不影响表单值的同步

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 11:30:00