我正在尝试创建删除我的待办事项的功能,但是当点击删除按钮时,没有任何反应,我的代码有什么问题吗,请帮助我!非常感谢!
import React, { useState } from "react";
function App() {
const [value, setValue] = useState("");
const [todos, setTodos] = useState([]);
// you can use the submit itself, no need for an extra addTodo function
handleSubmit = (e) => {
console.log("x");
e.preventDefault();
setTodos([...todos, value]);
setValue("");
};
deleteTodo = (id) => {
console.log("delete")
const removedArr = [...todos].filter(todo => todo.id !== id);
setTodos(removedArr);
}
return (
<div>
<form onSubmit={handleSubmit}>
<input
onChange={(e) => setValue(e.target.value)}
type="text"
placeholder="add todo"
/>
<button type="submit">Add</button>
</form>
{todos.map((todoValue) => (
<div>
{todoValue} <button deleteTodo={()=>deleteTodo(id)}>x</button>
</div>
))}
</div>
);
}
export default App;
链接代码和框:https://codesandbox.io/s/tender-cdn-cy3w4?file=/src/App.js:0-933
最佳答案
你的代码有两个错误:
- 当用户点击该按钮时,该按钮应调用 deleteTodo 函数,即 onClick() 函数
- id 未定义。 请引用这个沙箱代码示例。 我更正了您的代码,现在它可以正常工作了。 Link to sandbox
遵循在沙箱中编写的代码。
import React, { useState } from "react";
function App() {
const [value, setValue] = useState("");
const [todos, setTodos] = useState([]);
// you can use the submit itself, no need for an extra addTodo function
const handleSubmit = (e) => {
console.log("x");
e.preventDefault();
setTodos([...todos, value]);
setValue("");
};
const deleteTodo = (index) => {
console.log("delete");
const removedArr = [...todos].filter((todo, i) => index !== i);
setTodos(removedArr);
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
onChange={(e) => setValue(e.target.value)}
type="text"
placeholder="add todo"
/>
<button type="submit">Add</button>
</form>
{todos.map((todoValue, index) => (
<div>
{todoValue} <button onClick={() => deleteTodo(index)}>x</button>
</div>
))}
</div>
);
}
export default App;
关于reactjs - 为什么我不能使用过滤器删除我的待办事项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70553870/