>  기사  >  웹 프론트엔드  >  반응 js의 할 일 목록

반응 js의 할 일 목록

王林
王林원래의
2024-08-01 07:34:22302검색

Todo list in react js

LinkedIn에서 나를 팔로우하세요
Github.com에서 저를 팔로우하세요

클릭하여 읽기

이 간단한 Todo List 앱은 초보자가 상태 관리, 이벤트 처리, 목록 렌더링을 포함한 React의 기본 사항에 익숙해질 수 있는 훌륭한 시작점입니다.

React에서 Todo 목록 앱을 만드는 단계별 가이드

1단계: React 환경 설정

시작하기 전에 컴퓨터에 Node.js와 npm(또는 Yarn)이 설치되어 있는지 확인하세요. Create React App을 사용하여 새로운 React 프로젝트를 생성할 수 있습니다.

터미널이나 명령 프롬프트를 열고 다음 명령을 실행하여 새 React 프로젝트를 만듭니다.

npx create-react-app todo-list

프로젝트 디렉토리로 이동하세요:

cd todo-list

2단계: 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단계: 앱 실행

이제 다음 명령을 사용하여 Todo List 앱을 실행할 수 있습니다.

npm start

이 명령은 개발 서버를 시작하고 기본 웹 브라우저에서 새 React 애플리케이션을 엽니다.

즐거운 코딩하세요!

위 내용은 반응 js의 할 일 목록의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.