如何让MUI Autocomplete输入值统一转为Keyword类型对象?
解决MUI Autocomplete多标签模式下将输入字符串转为Keyword对象的问题
要实现用户按回车输入的内容自动转为Keyword对象,确保onChange回调中的tagsList始终为纯Keyword类型数组,只需通过以下几个关键修改即可完成:
关键修改步骤
1. 使用freeSoloValueTransform转换输入值
添加该属性将用户输入的字符串直接转换为Keyword对象,替代默认的字符串添加行为:
freeSoloValueTransform={(inputValue) => ({ label: inputValue, otherval: `"${inputValue}"` // 根据业务需求设置otherval字段值 })}
2. 简化getOptionLabel函数
现在所有选项均为Keyword类型,无需再处理字符串分支:
getOptionLabel={(option) => option.label}
3. 优化onChange回调逻辑
此时tagsList已全部是Keyword对象,直接处理即可:
onChange={(event, tagsList) => { // 提取所有标签的label const stringList = tagsList.map(item => item.label); console.log(stringList); // 也可直接操作完整的Keyword数组 console.log(tagsList); }}
4. 简化renderTags渲染逻辑
同样无需判断类型,直接读取option.label:
renderTags={(tagValues: readonly Keyword[], getTagProps) => tagValues.map((option, index) => ( <Chip sx={{ color: WHITE, background: BLUE, bgcolor: ROSA }} variant='outlined' label={option.label} {...getTagProps({ index })} /> )) }
5. 修复filterOptions的重复添加问题
原代码中无论输入值是否已存在都会添加自定义选项,调整后仅在值不存在时添加:
filterOptions={(options, params) => { const filtered = filter(options, params); const { inputValue } = params; const isExisting = options.some((option) => inputValue === option.label); if (inputValue !== '' && !isExisting) { filtered.push({ label: inputValue, otherval: `"${inputValue}"` }); } return filtered; }}
修改后的完整代码
<Autocomplete multiple freeSolo id='tags-filled' options={keywords} style={{ width: 600 }} freeSoloValueTransform={(inputValue) => ({ label: inputValue, otherval: `"${inputValue}"` })} onChange={(event, tagsList) => { const stringList = tagsList.map(item => item.label); console.log(stringList); console.log(tagsList); }} sx={{ color: BLACK, background: BLUE }} getOptionLabel={(option) => option.label} filterOptions={(options, params) => { const filtered = filter(options, params); const { inputValue } = params; const isExisting = options.some((option) => inputValue === option.label); if (inputValue !== '' && !isExisting) { filtered.push({ label: inputValue, otherval: `"${inputValue}"` }); } return filtered; }} renderOption={(props, option) => ( <span {...props} style={{ color: BLACK, backgroundColor: WHITE }}> {option.label} </span> )} renderTags={(tagValues: readonly Keyword[], getTagProps) => tagValues.map((option, index) => ( <Chip sx={{ color: WHITE, background: BLUE, bgcolor: ROSA }} variant='outlined' label={option.label} {...getTagProps({ index })} /> )) } renderInput={(params) => ( <TextField {...params} sx={{ color: WHITE, background: BLUE }} variant='filled' label='' style={{ flex: 1, margin: '0 50px 0 0', color: 'white' }} inputProps={{ style: { color: 'white' }, ...params.inputProps, }} placeholder='Product keywords' /> )} />
内容的提问来源于stack exchange,提问作者Rareform
相关产品推荐
相关产品推荐

