我正在react中构建一个简单的待办事项列表,我想在提交时存储元素。我知道handlessubmit()有问题,但无法解决。
import React, { useState } from "react";
function List() {
const [items, setItems] = useState([]);
const [item, setItem] = useState("");
function handleSubmit() {
setItems([ ...items, item ]);
console.log(items);
}
return (
<div>
<h3>To Do List</h3>
<form onSubmit={handleSubmit()}>
<input
value={item}
onChange={(event) => {
setItem(event.target.value);
}}
/>
<ul>
<li></li>
</ul>
<button type="submit">Add</button>
</form>
</div>
);
}
export default List;
<form onSubmit={handleSubmit()}>
应为<form onSubmit={handleSubmit}>
通过添加()
来调用handleSubmit
您正在直接调用handleSubmit
函数而不是传递其引用。把<form onSubmit={handleSubmit()}>
改成<form onSubmit={handleSubmit}>
您还需要防止默认表单提交操作。你可以在handlessubmit函数
中添加preventDefault行function handleSubmit(event) {
event.preventDefault();
setItems([ ...items, item ]);
console.log(items);
}