React 入门:从零搭建 TodoList 应用

本教程将带你逐步构建一个功能完整的 TodoList 应用,涵盖核心概念:组件设计、状态管理和事件处理。


步骤 1:环境准备
  1. 安装 Node.js(含 npm)
  2. 创建 React 项目:
npx create-react-app todo-list
cd todo-list
npm start


步骤 2:项目结构

关键文件:

  • src/App.js:主组件入口
  • src/index.js:渲染根组件
  • 新建 src/components/TodoList.js:存放核心逻辑

步骤 3:组件设计

3.1 状态定义(使用 useState 钩子)
TodoList.js 中初始化状态:

import React, { useState } from 'react';

function TodoList() {
  const [todos, setTodos] = useState([]); // 待办事项数组
  const [inputValue, setInputValue] = useState(''); // 输入框内容
}

3.2 渲染待办列表

return (
  <div>
    <h2>我的待办事项</h2>
    <ul>
      {todos.map((todo, index) => (
        <li key={index}>
          {todo.text}
          <button onClick={() => handleDelete(index)}>删除</button>
        </li>
      ))}
    </ul>
  </div>
);


步骤 4:事件处理

4.1 添加待办事项

const handleAdd = () => {
  if (inputValue.trim()) {
    setTodos([...todos, { text: inputValue }]);
    setInputValue(''); // 清空输入框
  }
};

// 在返回的 JSX 中添加输入框和按钮
<input
  type="text"
  value={inputValue}
  onChange={(e) => setInputValue(e.target.value)}
  placeholder="输入新任务"
/>
<button onClick={handleAdd}>添加</button>

4.2 删除待办事项

const handleDelete = (index) => {
  const newTodos = todos.filter((_, i) => i !== index);
  setTodos(newTodos);
};


步骤 5:完整组件代码

src/components/TodoList.js

import React, { useState } from 'react';

function TodoList() {
  const [todos, setTodos] = useState([]);
  const [inputValue, setInputValue] = useState('');

  const handleAdd = () => {
    if (inputValue.trim()) {
      setTodos([...todos, { text: inputValue }]);
      setInputValue('');
    }
  };

  const handleDelete = (index) => {
    setTodos(todos.filter((_, i) => i !== index));
  };

  return (
    <div>
      <h2>我的待办事项</h2>
      <div>
        <input
          type="text"
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          placeholder="输入新任务"
        />
        <button onClick={handleAdd}>添加</button>
      </div>
      <ul>
        {todos.map((todo, index) => (
          <li key={index}>
            {todo.text}
            <button onClick={() => handleDelete(index)}>删除</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default TodoList;

App.js 中引入:

import TodoList from './components/TodoList';

function App() {
  return (
    <div className="App">
      <TodoList />
    </div>
  );
}


步骤 6:效果优化
  1. 添加样式:在 src/index.css 中添加基础样式
ul { list-style: none; padding: 0; }
li { margin: 8px 0; padding: 8px; border: 1px solid #ddd; }
button { margin-left: 10px; }

  1. 键盘支持:按 Enter 键提交
<input
  // ...其他属性
  onKeyPress={(e) => e.key === 'Enter' && handleAdd()}
/>


核心概念总结
概念 作用 示例
组件 构建 UI 的独立单元 TodoList 函数组件
状态 存储动态数据 useState 管理待办列表
事件处理 响应用户交互 onClick, onChange
列表渲染 动态生成元素 todos.map() 循环

最终效果:

  • 输入任务 → 点击添加/按 Enter → 显示在列表中
  • 点击删除按钮移除任务

通过此项目,你已掌握 React 的核心工作流!下一步可扩展功能(如任务状态切换、本地存储等)。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐