MUI MobileDateTimePicker:实现键盘输入与图标触发选择器弹窗
解决MUI MobileDateTimePicker点击TextField自动弹窗的问题
要实现点击TextField可手动输入、仅点击右侧图标打开选择器的需求,你需要手动控制选择器的打开状态,并禁用TextField默认的触发弹窗行为,具体实现如下:
- 新增状态管理选择器的打开/关闭
- 覆盖TextField的默认事件,阻止获焦/点击时打开弹窗
- 绑定图标点击事件来触发弹窗
修改后的代码:
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
相关产品推荐
相关产品推荐

