gpt4 book ai didi

javascript - 使用 React 提交后要清除的输入表单

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

我创建了一个简单的待办事项列表,其中添加和删除有效。我的问题是,提交待办事项后,输入框不会清除。

这是我的 app.js

const App = () => {
const [toDoList, setToDoList] = useState([]);
const [toDo, setToDo] = useState("");

const handleToDo = (event) => {
const { value } = event.target;
setToDo(value);
};

const submit = () => {
//const list = toDoList;
const newItem = {
id: 1 + Math.random(),
value: toDo,
};
if (newItem.value && !toDoList.includes(newItem.value)) {
toDoList.push(newItem);
setToDoList([...toDoList]);
}
};

return (
<div className="container">
Add an Item
<br />
<input
type="text"
placeholder="Type item here..."
onChange={handleToDo}
/>
<button className="add-btn btn-floating" onClick={submit}>
<i class="material-icons"> + </i>
</button>
<br />
<ul>
...display of todos here
</ul>
</div>
);
//}
};

export default App;

我很困惑应该在哪里插入 useState 以便重置输入。

最佳答案

输入框的值也必须受国家管辖。所以输入应该是这样的:

<input
value={toDo}
type="text"
placeholder="Type item here..."
onChange={handleToDo}
/>

点击提交后,将待办事项重置为空

const submit = () => {
//const list = toDoList;
const newItem = {
id: 1 + Math.random(),
value: toDo,
};
if (newItem.value && !toDoList.includes(newItem.value)) {
toDoList.push(newItem);
setToDoList([...toDoList]);
}
setToDo("");
};

关于javascript - 使用 React 提交后要清除的输入表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68846266/

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