MUI v5 DateRangePicker 实现带可点击唤起面板的日历图标问题
解决Material UI v5 DateRangePicker添加可点击日历图标方案
你当前使用的mui/lab 5.0.0-alpha.50属于测试版本,API未对齐正式版文档,因此官方给出的components配置无法生效,手动加图标无法唤起弹窗是因为未绑定弹窗控制事件,以下是两种可行实现方案:
方案一:兼容测试版本的components配置
你需要保留renderInput参数的默认属性透传,不要手动覆盖InputProps即可生效,示例代码如下:
import { DateRangePicker } from '@mui/lab'; import CalendarTodayIcon from '@mui/icons-material/CalendarToday'; import TextField from '@mui/material/TextField'; import Box from '@mui/material/Box'; import { useState } from 'react'; function DateRangePickerDemo() { const [value, setValue] = useState([null, null]); return ( <DateRangePicker label="选择日期范围" value={value} onChange={(newValue) => { setValue(newValue); }} components={{ OpenPickerIcon: CalendarTodayIcon }} renderInput={(startProps, endProps) => ( <> <TextField {...startProps} /> <Box sx={{ mx: 2 }}>至</Box> <TextField {...endProps} /> </> )} /> ); }
方案二:手动控制弹窗状态(兼容性最高)
如果方案一仍不生效,可以通过state手动控制弹窗的开关,给自定义图标绑定点击事件即可,示例代码如下:
import { useState } from 'react'; import { DateRangePicker } from '@mui/lab'; import CalendarTodayIcon from '@mui/icons-material/CalendarToday'; import TextField from '@mui/material/TextField'; import Box from '@mui/material/Box'; import InputAdornment from '@mui/material/InputAdornment'; import IconButton from '@mui/material/IconButton'; function DateRangePickerDemo() { const [value, setValue] = useState([null, null]); const [open, setOpen] = useState(false); return ( <DateRangePicker open={open} onOpen={() => setOpen(true)} onClose={() => setOpen(false)} label="选择日期范围" value={value} onChange={(newValue) => { setValue(newValue); }} renderInput={(startProps, endProps) => ( <> <TextField {...startProps} /> <Box sx={{ mx: 2 }}>至</Box> <TextField {...endProps} InputProps={{ // 透传原有InputProps属性避免覆盖内置逻辑 ...endProps.InputProps, endAdornment: ( <InputAdornment position="end"> <IconButton onClick={() => setOpen(true)}> <CalendarTodayIcon /> </IconButton> </InputAdornment> ) }} /> </> )} /> ); }
内容的提问来源于stack exchange,提问作者Jonathan
相关产品推荐
相关产品推荐

