You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 14:45:36