最佳答案
我已经检索了使用 useState
存储在对象数组中的数据,然后将数据输出到表单字段中。现在我希望能够在输入时更新字段(状态)。
我见过一些例子,人们在数组中更新属性的状态,但是从来没有在对象的数组中更新状态,所以我不知道怎么做。我已经得到了传递给回调函数的对象的索引,但是我不知道如何使用它来更新状态。
// sample data structure
const datas = [
{
id: 1,
name: 'john',
gender: 'm'
}
{
id: 2,
name: 'mary',
gender: 'f'
}
]
const [datas, setDatas] = useState([]);
const updateFieldChanged = index => e => {
console.log('index: ' + index);
console.log('property name: '+ e.target.name);
setData() // ??
}
return (
<React.Fragment>
{datas.map((data, index) => {
<li key={data.name}>
<input type="text" name="name" value={data.name} onChange={updateFieldChanged(index)} />
</li>
})}
</React.Fragment>
)