React-Material-UI v6中DesktopDatePicker无renderInput及inputProp消失问题咨询
Material UI v6 自定义日期选择器输入框方案
MUI v6对日期选择器组件的API做了整合调整,原来v5里的inputProps和renderInput相关能力,现在通过slot系统来实现,具体方案如下:
1. 替代原inputProps配置输入框原生属性
在v6中,日期选择器的输入框是作为textField slot存在的,要设置输入框的原生属性,直接通过slotProps.textField.inputProps传递:
import { DateTimePicker } from '@mui/x-date-pickers/DateTimePicker'; import { TextField } from '@mui/material'; <DateTimePicker label="选择日期时间" value={value} onChange={(newValue) => setValue(newValue)} slotProps={{ textField: { inputProps: { // 这里写原来inputProps里的配置,比如禁用自动完成 autoComplete: 'off', // 自定义输入框placeholder placeholder: '请选择日期时间' } } }} />
2. 自定义渲染输入框(替代原renderInput)
如果需要完全自定义输入框的渲染逻辑,直接通过slots.textField替换默认的TextField组件即可,也可以基于原有TextField做二次封装:
import { DateTimePicker } from '@mui/x-date-pickers/DateTimePicker'; import { TextField, InputAdornment } from '@mui/material'; import CalendarTodayIcon from '@mui/icons-material/CalendarToday'; // 自定义输入框组件 const CustomTextField = (props) => { return ( <TextField {...props} variant="outlined" InputProps={{ endAdornment: ( <InputAdornment position="end"> <CalendarTodayIcon /> </InputAdornment> ) }} /> ); }; // 使用自定义输入框的DateTimePicker <DateTimePicker label="选择日期时间" value={value} onChange={(newValue) => setValue(newValue)} slots={{ textField: CustomTextField }} />
补充说明
v6中已经取消了DesktopDatePicker这类按设备区分的组件,统一使用DatePicker、DateTimePicker,组件会自动根据设备适配桌面/移动端样式,无需手动区分。
内容的提问来源于stack exchange,提问作者Terraya
相关产品推荐
相关产品推荐

