react实现todolist
实现React TodoList的基本步骤
创建React TodoList需要理解组件结构、状态管理和用户交互逻辑。以下是实现一个基础TodoList的详细方法。
初始化React项目
使用Create React App或Vite初始化项目。以Create React App为例,运行以下命令:
npx create-react-app todo-list
cd todo-list
npm start
创建核心组件结构
设计两个主要组件:TodoList(父组件)和TodoItem(子项)。在src目录下创建对应文件。
状态管理
在TodoList.js中使用useState管理任务列表和输入框内容:
import React, { useState } from 'react';
function TodoList() {
const [todos, setTodos] = useState([]);
const [inputValue, setInputValue] = useState('');
}
处理用户输入
添加输入框和按钮的交互逻辑:
const handleInputChange = (e) => {
setInputValue(e.target.value);
};
const handleAddTodo = () => {
if (inputValue.trim()) {
setTodos([...todos, { text: inputValue, completed: false }]);
setInputValue('');
}
};
渲染任务列表
映射todos数组生成任务项,并添加删除和完成状态切换功能:
const handleDelete = (index) => {
const newTodos = todos.filter((_, i) => i !== index);
setTodos(newTodos);
};
const handleToggleComplete = (index) => {
const newTodos = todos.map((todo, i) =>
i === index ? { ...todo, completed: !todo.completed } : todo
);
setTodos(newTodos);
};
完整组件代码示例
TodoList.js完整实现:
import React, { useState } from 'react';
function TodoList() {
const [todos, setTodos] = useState([]);
const [inputValue, setInputValue] = useState('');
const handleInputChange = (e) => {
setInputValue(e.target.value);
};
const handleAddTodo = () => {
if (inputValue.trim()) {
setTodos([...todos, { text: inputValue, completed: false }]);
setInputValue('');
}
};
const handleDelete = (index) => {
const newTodos = todos.filter((_, i) => i !== index);
setTodos(newTodos);
};
const handleToggleComplete = (index) => {
const newTodos = todos.map((todo, i) =>
i === index ? { ...todo, completed: !todo.completed } : todo
);
setTodos(newTodos);
};
return (
<div>
<h1>Todo List</h1>
<input
type="text"
value={inputValue}
onChange={handleInputChange}
placeholder="Add new task"
/>
<button onClick={handleAddTodo}>Add</button>
<ul>
{todos.map((todo, index) => (
<li key={index} style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}>
{todo.text}
<button onClick={() => handleToggleComplete(index)}>
{todo.completed ? 'Undo' : 'Complete'}
</button>
<button onClick={() => handleDelete(index)}>Delete</button>
</li>
))}
</ul>
</div>
);
}
export default TodoList;
样式优化
添加基础CSS增强视觉效果。在App.css中添加:
.todo-item {
margin: 5px 0;
padding: 5px;
display: flex;
align-items: center;
}
.todo-text {
flex-grow: 1;
margin: 0 10px;
}
button {
margin-left: 5px;
cursor: pointer;
}
功能扩展建议
- 使用
localStorage持久化存储任务数据 - 添加任务分类或标签功能
- 实现拖拽排序任务项
- 添加任务优先级标记
- 使用Context API或Redux管理全局状态
以上实现提供了React TodoList的核心功能,可根据需求进一步扩展和完善。







