如何在react-final-form中使用带标签的Material UI Autocomplete
解决方案
核心要解决两种值格式的双向绑定问题:Field存储的是后端返回的逗号分隔字符串,多选模式的Autocomplete需要数组格式的值,选中变更时还要把数组转回字符串同步给表单。
修改后的完整可运行代码:
import { Chip, TextField, Autocomplete } from '@mui/material'; import { Field } from 'react-final-form'; // 提前定义好的选项常量 // const top100Films = [...] export const AutocompleteFreeSolo: React.FC<{ source: string; initialValue?: string }> = ({ source, initialValue, }) => { return ( <Field type="text" name={source} defaultValue={initialValue}> {({ input }) => { // 表单字符串转组件需要的数组格式 const selectedList = input.value ? input.value.split(',').map(item => item.trim()).filter(Boolean) : []; return ( <Autocomplete multiple id="tags-filled" options={top100Films.map((option: any) => option.title)} freeSolo value={selectedList} onChange={(_, newVal) => { // 组件数组转回逗号分隔字符串,同步回表单 input.onChange(newVal.join(',')); }} onBlur={input.onBlur} renderTags={(value: readonly string[], getTagProps) => value.map((option: string, index: number) => ( <Chip key={index} variant="outlined" label={option} {...getTagProps({ index })} /> )) } renderInput={(params) => ( <TextField {...params} variant="filled" label="freeSolo" placeholder="Favorites" name={input.name} /> )} /> ); }} </Field> ); };
关键逻辑说明
- 入值转换:从Field的
input.value拿到原始字符串后,按逗号拆分,同时做了去前后空格、过滤空值处理,避免渲染出空白Chip。 - 出值同步:Autocomplete选中项变化时,把选中的字符串数组重新拼接为逗号分隔的字符串,调用
input.onChange回传给表单,保证表单提交时拿到的格式和后端要求一致。 - 状态兼容:额外绑定了
onBlur和字段name属性,兼容表单的touched状态校验、字段识别逻辑,不会出现校验状态异常的问题。 - 渲染优化:给列表渲染的Chip补充了key属性,消除React的列表渲染警告。
内容的提问来源于stack exchange,提问作者Tigran
相关产品推荐
相关产品推荐

