如何在表单输入框中正确接收数组数据并实现独立编辑
解决方案
你的问题核心是把数组直接拼接成字符串传给输入框,导致无法独立操作每个项。通过以下修改可以实现你要的效果:
关键修改点
- 启用Autocomplete的
multiple属性,让它直接处理数组类型的值 - 移除数组转字符串的
join(', '),直接传入原始数组作为默认值 - 自定义渲染每个数组项为可删除的Chip组件,实现单独删除功能
修改后的代码示例
import React, { useState } from "react"; import TextField from "@mui/material/TextField"; import Autocomplete from "@mui/material/Autocomplete"; import Chip from "@mui/material/Chip"; const top100Films = [ { title: "The Shawshank Redemption", year: 1994 }, { title: "The Godfather", year: 1972 }, { title: "The Godfather: Part II", year: 1974 }, { title: "The Dark Knight", year: 2008 }, { title: "12 Angry Men", year: 1957 }, { title: "Schindler's List", year: 1993 }, { title: "Pulp Fiction", year: 1994 }, // 其他选项可保留原数据 ]; export default function App() { const [names, setNames] = useState(["Alice", "Bob", "Charlie"]); return ( <div className="App"> <h1>Edit Form</h1> <Autocomplete multiple id="tags-outlined" defaultValue={names} value={names} options={top100Films.map((option) => option.title)} onChange={(event, newValue) => { setNames(newValue); }} renderTags={(value, getTagProps) => value.map((option, index) => ( <Chip key={index} label={option} onDelete={() => { const newValues = [...value]; newValues.splice(index, 1); setNames(newValues); }} {...getTagProps({ index })} /> )) } renderInput={(params) => ( <TextField {...params} variant="outlined" label="Names" placeholder="Add a name" fullWidth /> )} /> <button onClick={() => console.log("Submitted:", names)}>Submit</button> </div> ); }
效果说明
- 每个数组项会以独立的Chip形式显示,支持单独点击删除按钮移除该项
- 自动补全功能正常工作,添加新名称时会追加到数组中,不会影响已存在的值
- 提交表单时,
names状态会保留完整的数组数据,不会出现拼接问题
内容的提问来源于stack exchange,提问作者Coraggio
相关产品推荐
相关产品推荐

