首页  >  文章  >  web前端  >  React js 中的待办事项列表

React js 中的待办事项列表

王林
王林原创
2024-08-01 07:34:22306浏览

Todo list in react js

在 LinkedIn 上关注我
在 Github.com 上关注我

点击阅读

这个简单的待办事项列表应用程序是初学者熟悉 React 基础知识的一个很好的起点,包括状态管理、事件处理和渲染列表。

在 React 中创建待办事项列表应用程序的分步指南

第 1 步:设置你的 React 环境

开始之前,请确保您的计算机上安装了 Node.js 和 npm(或yarn)。您可以使用 Create React App 创建一个新的 React 项目。

打开终端或命令提示符并运行以下命令来创建一个新的 React 项目:

npx create-react-app todo-list

导航到项目目录:

cd todo-list

第二步:修改src/App.js

将 src/App.js 的内容替换为以下代码:

import React, { useState } from 'react';
import './App.css';

function App() {
  const [todos, setTodos] = useState([]);
  const [input, setInput] = useState('');

  const handleInputChange = (e) => {
    setInput(e.target.value);
  };

  const handleAddTodo = () => {
    if (input.trim()) {
      setTodos([...todos, { text: input, completed: false }]);
      setInput('');
    }
  };

  const handleToggleComplete = (index) => {
    const newTodos = todos.map((todo, i) => {
      if (i === index) {
        return { ...todo, completed: !todo.completed };
      }
      return todo;
    });
    setTodos(newTodos);
  };

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

  return (
    <div className="App">
      <header className="App-header">
        <h1>Todo List</h1>
        <div>
          <input
            type="text"
            value={input}
            onChange={handleInputChange}
            placeholder="Add a new todo"
          />
          <button onClick={handleAddTodo}>Add</button>
        </div>
        <ul>
          {todos.map((todo, index) => (
            <li key={index}>
              <span
                style={{
                  textDecoration: todo.completed ? 'line-through' : 'none',
                }}
                onClick={() => handleToggleComplete(index)}
              >
                {todo.text}
              </span>
              <button onClick={() => handleDeleteTodo(index)}>Delete</button>
            </li>
          ))}
        </ul>
      </header>
    </div>
  );
}

export default App;

第 3 步:添加一些基本样式

修改 src/App.css 文件以添加一些基本样式:

.App {
  text-align: center;
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

input {
  padding: 10px;
  margin-right: 10px;
  font-size: 16px;
}

button {
  padding: 10px;
  font-size: 16px;
  cursor: pointer;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  margin: 10px 0;
  background-color: #444;
  border-radius: 5px;
}

li span {
  cursor: pointer;
}

第 4 步:运行应用程序

现在,您可以使用以下命令运行您的待办事项列表应用程序:

npm start

此命令启动开发服务器并在默认 Web 浏览器中打开新的 React 应用程序。

编码快乐!

以上是React js 中的待办事项列表的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn