jsx
import React, { useState } from 'react';
function TodoList() {
const [todos, setTodos] = useState([]);
const [input, setInput] = useState('');
// 添加任务
const handleAddTodo = () => {
if (input.trim() === '') return;
setTodos([
...todos,
{ text: input, completed: false, id: Date.now() }
]);
setInput('');
};
// 删除任务
const handleDeleteTodo = (id) => {
setTodos(todos.filter(todo => todo.id !== id));
};
// 切换完成状态
const handleToggleTodo = (id) => {
setTodos(
todos.map(todo =>
todo.id === id ? { ...todo, completed: !todo.completed } : todo
)
);
};
return (
<div style={{ maxWidth: 400, margin: '0 auto' }}>
<h2>Todo List</h2>
<div>
<input
value={input}
onChange={e => setInput(e.target.value)}
onKeyDown={e => e.key === 'Enter' && handleAddTodo()}
placeholder="添加新任务"
/>
<button onClick={handleAddTodo}>添加</button>
</div>
<ul style={{ listStyle: 'none', padding: 0 }}>
{todos.map(todo => (
<li key={todo.id} style={{ margin: '8px 0', display: 'flex', alignItems: 'center' }}>
<input
type="checkbox"
checked={todo.completed}
onChange={() => handleToggleTodo(todo.id)}
/>
<span
style={{
textDecoration: todo.completed ? 'line-through' : 'none',
flex: 1,
marginLeft: 8
}}
>
{todo.text}
</span>
<button onClick={() => handleDeleteTodo(todo.id)} style={{ marginLeft: 8 }}>
删除
</button>
</li>
))}
</ul>
</div>
);
}
export default TodoList;