更改数组内对象的单个属性



我的React项目中有这样的状态:

const [information, setInformation] = React.useState([
{
Email: "",
TellNo: "",
Username: "",
NationalityType: "",
pIDCheck: "",
VerificationCode: "",
Password: "",
},
]);

我想更新";TellNo";输入值更改时的值。我尝试了很多这样的方法:

onChange={(e) =>
setInformation((prev) => [{...prev, TellNo: e.target.value }])
}

但正如你所看到的。它将添加一个附加对象。如何在不添加对象的情况下更改TellNo

只需执行以下代码:

const [information, setInformation] = React.useState({
Email: "",
TellNo: "",
Username: "",
NationalityType: "",
pIDCheck: "",
VerificationCode: "",
Password: "",
});

onChange={(e) =>
setInformation({...information, TellNo: e.target.value})
}

当你想发送信息时,你可以在一个数组中传递:

[information]

使用您当前的结构,您可以尝试如下。。。

onChange={(e) =>
setInformation([{...information[0], TellNo: e.target.value }])
}

最新更新