在表单Submit上反应useState-挂钩

时间:2020-06-17 05:35:27

标签: reactjs react-hooks

我想在OnChange事件上提交一个输入。到目前为止,我做了下面的代码:

<form onSubmit={onSubmitHandler}>
        <Input className="form-control mb-3" type="text" name="name" placeholder="Enter To Do Items"/>
        <Button classProp="btn btn-warning btn-block">Submit</Button>
</form>

const [toDoName, setToDoName] = useState([]);

const onSubmitHandler = (event) => {
    event.preventDefault();
    setToDoName( prevState => [
        ...prevState,
        event.target['name'].valueame
    ])
}

如何设置提交状态

1 个答案:

答案 0 :(得分:1)

Synthetic events are pooled by React for reuse,并且由于您在功能状态更新中使用了事件值,因此在更新发生之前清除事件值会引发错误。保存状态值,然后再更新状态或使用event.persist()保留事件值

const onSubmitHandler = (event) => {
    event.preventDefault();
    const value = event.target['name'].valueame; // make sure you use correct property from event
    setToDoName( prevState => [
        ...prevState,
        value
    ])
}