gpt4 book ai didi

javascript - React 功能组件 状态对象的表单处理

转载 作者:行者123 更新时间:2023-12-02 21:09:44 24 4
gpt4 key购买 nike

所以我尝试在 React 中创建一个带有功能组件的表单。我有一个包含对象的状态

const [event, setEvent] = useState(props.location.event);
{
"id": 1,
"limit": 2000,
"price": 10,
"accessLvl": 0,
"details": "Event that contains all the fields",
"duration": 24,
"eventType": 1,
"eventLocation": "asdasd",
"creator": 1,
"startDate": "2020-06-01T12:00:00",
"title": "Testing update",
"imageUrl": "d0659c5e-7ca1-4b02-b148-6221d6e7d7a8"
}

这是一个编辑表单,因此我将输入值设置为这些变量。使用类组件,我可以轻松地做到这一点,但是使用功能组件,当我尝试更改一个变量(例如标题)时,对象只会包含标题,这不是我想要的行为。

<input type="text" className="form-control" value={props.event.title} onChange={e => props.onTodoChange(e.target.value, "title")} id="EventTitle" />

function onTodoChange(value, key) {
setEvent({[key] : value})
}

最佳答案

这行得通吗?

function onTodoChange(value, key) {
setEvent(ev => ({
...ev,
[key] : value,
}))
}

函数setEvent可以采用一个带有一个参数的函数,该参数是前一个事件...evev 的所有属性复制到新对象中,然后使用 [key] : value 覆盖所需的属性.

关于javascript - React 功能组件 状态对象的表单处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61128881/

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