如何实现MUI Autocomplete选项居中并添加边框?
MUI Autocomplete选项居中与添加边框解决方案
你定义了CustomListbox但未将其绑定到Autocomplete的ListboxComponent属性,导致样式不生效。同时需要在选项样式中补充边框相关设置,以下是修改后的完整代码:
const PlacementCell = ({ value, placements, notAvailable = false, readOnly = false }: PlacementCellProps): ReactElement => { const { palette, spacing } = useTheme(); const [selectedPlacement, setSelectedPlacement] = useState<Placement | undefined>(value || placements[0]); const handlePlacementChange = (event: React.SyntheticEvent, newValue: Placement | null) => { if (newValue !== null) { setSelectedPlacement(newValue); } }; const CustomListbox = styled('ul')({ [`& .${autocompleteClasses.option}`]: { display: 'flex', justifyContent: 'center', // 添加边框样式 border: '1px solid #e0e0e0', borderRadius: '4px', marginBottom: spacing(1), padding: spacing(1), // 适配选中状态样式(可选) '&.Mui-selected': { backgroundColor: palette.action.selected, }, }, // 调整列表容器内边距,优化选项排版 padding: spacing(1), }); return ( <Stack direction="row" height={1} alignItems="center" spacing={2} justifyContent="space-between" > <Autocomplete options={placements} getOptionLabel={(option) => option.placementName} renderInput={(params) => ( <TextField placeholder="Select" {...params} InputProps={{ ...params.InputProps, disableUnderline: true, }} inputProps={{ ...params.inputProps, style: { textAlign: 'center' }, }} sx={{ [`& .${autocompleteClasses.inputRoot} .MuiInput-input`]: { padding: '12px', }, variant: 'bodySmall.default', [`& .${autocompleteClasses.popupIndicator}`]: { right: 12, ['&:hover']: { backgroundColor: 'transparent', }, }, }} /> )} // 绑定自定义列表容器组件,使样式生效 ListboxComponent={CustomListbox} fullWidth disableClearable onChange={handlePlacementChange} /> </Stack> ); };
关键修改说明:
- 绑定自定义容器:给Autocomplete添加
ListboxComponent={CustomListbox},让自定义样式作用到下拉选项列表 - 选项居中:通过
justifyContent: 'center'实现选项文本水平居中 - 边框设置:给选项添加
border、borderRadius,配合marginBottom和padding调整间距与内边距,优化视觉效果 - 主题适配:可将固定颜色
#e0e0e0替换为palette.divider等主题变量,保持整体风格统一
内容的提问来源于stack exchange,提问作者mariadev
相关产品推荐
相关产品推荐

