handleChangeUpdate
函数适用于单个输入,例如 name
。
但是当添加第二个输入(例如 description
)时,无论输入 name
还是 description
输入,两个输入都会收到相同的值。
我如何让每个输入都接收到它自己的值?
const F = () => {
const initialList = [
{
id: "a",
name: "John",
description: "1as23"
},
{
id: "b",
name: "Eric",
description: "12ce3"
},
{
id: "c",
name: "Jonathan",
description: "12vt3"
},
];
const [list, setList] = React.useState(initialList);
const [name, setName] = React.useState("");
const [description, setDescription] = React.useState("");
function handleChangeUpdate(id, value, description) {
const newList = list.map((item) => {
if (item.id === id) {
const updatedItem = {
...item,
name: value,
description: value
};
return updatedItem;
}
return item;
});
setList(newList);
console.log(newList);
}
return (
<div>
<ul >
<div>
{list.map((item) => (
<li key={item.id}>
<input className="form-control" onChange={(e)=> handleChangeUpdate(item.id, e.target.name)} defaultValue={item.name}></input>
<input className="form-control" onChange={(e)=> handleChangeUpdate(item.id, e.target.description)} defaultValue={item.description}></input>
</li>
))}
</div>
</ul>
</div>
);
};
ReactDOM.render(<F />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.0/umd/react-dom.production.min.js"></script>
<div id="app"></div>