MUI自定义主题如何全局配置Autocomplete标签默认shrink
在使用Material UI(MUI)时,我们可以通过自定义主题配置让TextField的标签默认处于收缩状态,对应主题配置代码如下:
MuiTextField: { defaultProps: { InputLabelProps: { shrink: true } }, },
但将TextField与Autocomplete组件搭配使用时,示例代码如下:
<Autocomplete fullWidth options={options} clearOnBlur disablePortal popupIcon={false} id="combo-box-demo" renderInput={params => { return ( <TextField {...params} label="Movie" variant="standard" /> ); }} />

上述针对TextField的全局配置不会生效,标签不会默认收缩。目前可使用的临时解决方案是在Autocomplete的renderInput属性中手动传入InputLabelProps配置,代码如下:
renderInput={({ InputLabelProps, ...params })=> { return ( <TextField {...params} label="Movie" variant="standard" InputLabelProps={{ shrink: true, ...InputLabelProps, }} /> ); }}
这种方案存在明显缺陷:每次使用Autocomplete都需要手动传入该配置,很容易遗漏。预想的全局配置写法如下,需要确认该配置方式是否可行,能否通过自定义主题全局实现Autocomplete内标签默认收缩的效果:
MuiAutoComplete: { defaultProps: { InputLabelProps: { shrink: true } }, },
你预想的配置写法不可行,首先存在拼写错误:MUI主题中Autocomplete对应的组件key是MuiAutocomplete(Complete首字母为小写c);其次就算修正拼写,直接给MuiAutocomplete挂载InputLabelProps默认属性也不会生效——Autocomplete组件本身不消费InputLabelProps属性,不会自动把该属性合并到renderInput的参数中透传给内部输入组件。
可以通过以下两种方案实现全局配置效果,按需选择即可:
- 方案1:重写Autocomplete默认renderInput(推荐)
在主题配置中给MuiAutocomplete设置全局默认的renderInput逻辑,把标签收缩配置内置,所有未自定义renderInput的Autocomplete场景都会自动生效:import { TextField } from '@mui/material'; // 主题配置中添加 MuiAutocomplete: { defaultProps: { renderInput: (params) => ( <TextField {...params} InputLabelProps={{ shrink: true, ...params.InputLabelProps }} /> ) } } - 方案2:全局设置InputLabel默认属性
标签收缩状态本质由InputLabel组件的shrink属性控制,直接全局给InputLabel设置默认值,无论是单独使用TextField还是Autocomplete内的输入标签都会统一生效,配置更简洁:MuiInputLabel: { defaultProps: { shrink: true } }注意:该方案会让项目内所有InputLabel默认保持收缩状态,如果存在需要标签浮动不收缩的特殊场景,需要单独给对应组件传入
InputLabelProps={{shrink: false}}覆盖配置。
内容的提问来源于stack exchange,提问作者Bryan Lumbantobing

