Material UI Autocomplete filled变体自定义endInputAdornment不居中如何解决
问题原因
Material UI 中 variant="filled" 的 <TextField> 为了适配顶部悬浮的标签样式,输入框外层容器的 adornment 区域默认采用顶部对齐规则,默认内置的 popupIcon 已经做了专属偏移适配,你自定义添加的 IconButton 没有对应对齐规则,因此会出现偏移。
解决方案
你可以直接给自定义添加的 IconButton 增加 alignSelf: 'center' 的样式规则,无需修改原有默认popupIcon的任何属性,也不会影响组件原有功能:
<Autocomplete disablePortal id="combo-box-demo" options={top100Films} sx={{ width: 300, mt: 2 }} renderInput={(params) => ( <TextField {...params} label="Movie" variant="filled" InputProps={{ ...params.InputProps, endAdornment: ( <React.Fragment> {params.InputProps.endAdornment} {/* 仅需给自定义IconButton添加sx属性即可 */} <IconButton color="primary" aria-label="upload picture" component="span" sx={{ alignSelf: 'center' }} > <PhotoCamera /> </IconButton> </React.Fragment> ) }} /> )} />
如果需要添加多个自定义图标,可以统一用一个flex容器包裹,只给外层容器加一次对齐规则即可:
endAdornment: ( <React.Fragment> {params.InputProps.endAdornment} <Box sx={{ alignSelf: 'center', display: 'flex', gap: 0.5 }}> <IconButton color="primary" aria-label="upload picture" component="span" > <PhotoCamera /> </IconButton> {/* 可继续添加其他自定义按钮 */} </Box> </React.Fragment> )
内容的提问来源于stack exchange,提问作者Henrik Maaland
相关产品推荐
相关产品推荐

