來完成一個 Todo List 吧!
import { useState } from "react";
function TodoList() {
const [todos, setTodos] = useState([]);
const [task, setTask] = useState("");
const addTodo = () => {
if (task.trim() !== "") {
const newTodo = { text: task, completed: false };
const newTodos = [...todos, newTodo];
console.log(newTodos);
setTodos(newTodos);
setTask("");
}
};
const filterTodo = todos;
return (
<div>
<div>
<input
text="text"
value={task}
onChange={(e) => setTask(e.target.value)}
placeholder="請輸入待辦事項"
/>
<button onClick={addTodo}>新增</button>
</div>
<ul>
<li>
<label>
<input type="checkbox" className="input-control" />
item-01
</label>
</li>
</ul>
</div>
);
}
export default TodoList;
map()
把 <li>...</li>
渲染出來 <ul>
{filterTodo.map((todo, index) => (
<li key={index}>
<label>
<input
type="checkbox"
/>
{todo.text}
</label>
</li>
))}
</ul>
```
- 第二階段的結果
![img](https://i.imgur.com/ULXkBSd.gif)
## 第三階段 - 把勾選的項目勾選後視為完成
- 在 checkbox 上面新增一個 onChanage() 動作,他將執行 `toggleComplete`
toggleComplete
執行的內容是將 completed
做 true
和 false
的變化 const toggleComplete = (index) => {
const updatedTodos = [...todos];
updatedTodos[index].completed = !updatedTodos[index].completed;
setTodos(updatedTodos);
};
useState(),並且給預設值為
all`const [filter, setFilter] = useState("all");
const filterTodo = todos.filter((todo) => {
if (filter === "todo") {
return !todo.completed;
} else if (filter === "completed") {
return todo.completed;
} else {
return true;
}
});
onClick()
時,會傳入 setFilter 對應的值<div>
<button onClick={() => setFilter("all")}>全部</button>
<button onClick={() => setFilter("todo")}>待處理</button>
<button onClick={() => setFilter("completed")}>已完成</button>
</div>
完成啦!
這邊附上最終完整程式碼