gpt4 book ai didi

javascript - 如何从对象类型 State 的字段捕获 onChange 事件

转载 作者:行者123 更新时间:2023-12-02 01:38:01 27 4
gpt4 key购买 nike

我无法从本身包含多个对象字段的对象捕获 onChange 事件。

这是我的 useState Hook 。

    const [train, setTrain] = useState({
trainNumber: "",
trainName: "",
fromStation: "",
toStation: "",
departureDateTime: "",
arrivalDateTime: "",
//unable to capture travelDetails property changes.
travelDetails: {
coachesClass: [
{
availableTickets: "",
travelClass: "",
fare: "",
},
],
},
});

假设我想检查 tripDetails.coachesClass[0].availableTickets 的 onChange 事件,那么该怎么做?

        <div className="row">
<label htmlFor="availableTickets">First AC</label>
<div className="col-4">
<input
type="number"
name="availableTickets"
className="form-control"
placeholder="Available Tickets"
required
value={train.travelDetails.coachesClass[0].availableTickets}
onChange={(e) => handleChange(e)}
/>
</div>

这是 onChangeHandler

const handleChange = (e) => {
const { name, value } = e.target;
setTrain((prevState) => {
return {
...prevState,
[name]: value,
};
});

};

它对于其他字段工作正常,但在 TravelDetails 内部它没有捕获更改。

最佳答案

由于您尝试更新嵌套在对象内的数组中的属性,因此需要调整更新状态的方式。尝试这样的事情:

  const handleChange = (e) => {
setTrain((prevState) => {
const newCoachesClass = [...prevState.travelDetails.coachesClass];
newCoachesClass[0] = {
...prevState.travelDetails.coachesClass[0],
availableTickets: e.target.value
};
return {
...prevState,
travelDetails: {
...prevState.travelDetails,
coachesClass: newCoachesClass
}
};
});
};

此外,由于您的输入数字类型,您可能希望将availableTickets初始化为数字而不是字符串:

const [train, setTrain] = useState({
trainNumber: "",
trainName: "",
fromStation: "",
toStation: "",
departureDateTime: "",
arrivalDateTime: "",
travelDetails: {
coachesClass: [
{
availableTickets: 0,
...

查看此 codepen 的示例:Edit React-Update-Nested-State-Array

关于javascript - 如何从对象类型 State 的字段捕获 onChange 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72033033/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com