如何将Material UI多选Autocomplete改为紧凑的下拉多选样式
实现Material UI多选Autocomplete的紧凑逗号分隔显示效果
要实现多选值以逗号分隔的紧凑显示(类似原生多选Select),核心是通过renderTags自定义选中项的渲染逻辑,替代默认的标签展开布局,同时调整样式适配紧凑效果。以下是修改后的完整代码:
<Autocomplete disablePortal id="serviceCities" name="serviceCities" value={formik.values.serviceCities} onChange={(e, value) => formik.setFieldValue("serviceCities", value)} options={cities} loading={true} loadingText="loading..." multiple={true} getOptionLabel={type => type.name} sx={{ width: "100%", mt: "4%", // 调整输入框内边距,适配紧凑显示 '& .MuiAutocomplete-inputRoot': { padding: '8px 14px', } }} isOptionEqualToValue={(option, value) => option.id === value.id} // 自定义选中项渲染:拼接为逗号分隔文本 renderTags={(value, getTagProps) => { if (value.length === 0) return null; const joinedLabels = value.map(item => getOptionLabel(item)).join(', '); return ( <span {...getTagProps({})} style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }} > {joinedLabels} </span> ); }} renderInput={(params) => ( <TextField {...params} label="provide services in" placeholder="type name of cities" sx={{ ...styles.autoComplete, width: "100%" }} InputLabelProps={{ shrink: true }} error={formik.touched.serviceCities && Boolean(formik.errors.serviceCities)} helperText={formik.touched.serviceCities && formik.errors.serviceCities} // 重置输入框内边距,消除默认标签布局的影响 InputProps={{ ...params.InputProps, style: { ...params.InputProps.style, padding: 0, }, }} /> )} />
关键修改说明
renderTags自定义渲染:将选中的所有选项名称拼接为逗号分隔的字符串,用<span>包裹并添加文本溢出省略样式,确保内容过长时不会撑大输入框。- 样式适配:通过
sx调整Autocomplete输入根容器的内边距,同时重置TextField的InputProps内边距,完全消除默认多选标签带来的额外间距,保持输入框紧凑。 - 保留原有功能:Formik表单绑定、选项匹配、加载状态等原有逻辑均保持不变,仅修改显示方式。
内容的提问来源于stack exchange,提问作者Rachel
相关产品推荐
相关产品推荐

