首頁  >  文章  >  web前端  >  React js 中的待辦事項列表

React js 中的待辦事項列表

王林
王林原創
2024-08-01 07:34:22302瀏覽

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