【React】实现一个简单的待办事项列表

如何使用React 实现一个简单的待办事项列表?

本文会从如何搭建一个React环境开始写起,直到能运行出一个简单的待办事项列表,完成用户可以添加、编辑和删除待办事项的功能。

首先是在本地配置React开发环境的详细步骤:

  1. 安装Node.js:访问Node.js官方网站(https://nodejs.org/) 下载并安装适用于您操作系统的最新版本的Node.js。安装完成后,您可以在命令行中运行node -v来检查Node.js是否成功安装。
    在这里插入图片描述

  2. 选择代码编辑器:选择一个适合您的代码编辑器,例如Visual Studio Code、HBuilderX等。确保您已经在计算机上安装了您选择的代码编辑器,本文使用的是HBuilderX。

  3. 下载相关React的包:npm install -g create-react-app

  4. 创建新的React项目:打开命令行终端,并导航到您想要创建React项目的目录。运行以下命令来创建一个新的React项目:

create-react-app project_name

这将创建一个名为my-app的新目录,并在其中初始化一个新的React项目。

  1. 进入项目目录:在命令行中运行以下命令,进入新创建的React项目的目录:
cd project_name
  1. 启动开发服务器:运行以下命令来启动React开发服务器:
npm start

这将启动一个本地开发服务器,并在浏览器中打开http://localhost:3000,能够看到React应用程序的初始页面。

本地跑的示例(具体过程):

在这里插入图片描述

出现这样的画面即为成功

屏幕截图 2023-08-12 104950.png

  1. 简单的待办事项列表具体实现:
    编辑React应用程序:第一步:打开React项目文件夹中的src/App.css文件
.App {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  text-align: center;
}

.add-todo {
  display: flex;
  margin-bottom: 20px;
}

.input {
  flex: 1;
  padding: 10px;
  border: none;
  border-radius: 5px;
  font-size: 16px;
}

.button {
  padding: 10px 20px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
}

.todo-list {
  list-style: none;
  padding: 0;
}

.todo-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
  padding: 10px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.actions {
  display: flex;
}

.edit-button {
  margin-right: 5px;
  background-color: #ffc107;
}

.delete-button {
  background-color: #dc3545;
}

打开React项目文件夹中的src/App.js文件,并对其进行编辑。

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

function App() {
  const [todos, setTodos] = useState([]);
  const [newTodo, setNewTodo] = useState('');
  const [editingIndex, setEditingIndex] = useState(-1);

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

  const handleAddTodo = () => {
    if (newTodo.trim() !== '') {
      setTodos([...todos, newTodo]);
      setNewTodo('');
    }
  };

  const handleEditTodo = (index) => {
    setEditingIndex(index);
    setNewTodo(todos[index]);
  };

  const handleUpdateTodo = () => {
    if (newTodo.trim() !== '') {
      const updatedTodos = [...todos];
      updatedTodos[editingIndex] = newTodo;
      setTodos(updatedTodos);
      setNewTodo('');
      setEditingIndex(-1);
    }
  };

  const handleDeleteTodo = (index) => {
    const updatedTodos = [...todos];
    updatedTodos.splice(index, 1);
    setTodos(updatedTodos);
  };

  return (
    <div className="App">
      <h1 className="title">Todo List</h1>
      <div className="add-todo">
        <input
          type="text"
          className="input"
          placeholder="Add todo..."
          value={newTodo}
          onChange={handleInputChange}
        />
        {editingIndex !== -1 ? (
          <button className="button" onClick={handleUpdateTodo}>
            Update
          </button>
        ) : (
          <button className="button" onClick={handleAddTodo}>
            Add
          </button>
        )}
      </div>
      <ul className="todo-list">
        {todos.map((todo, index) => (
          <li key={index} className="todo-item">
            <span>{todo}</span>
            <div className="actions">
              <button
                className="button edit-button"
                onClick={() => handleEditTodo(index)}
              >
                Edit
              </button>
              <button
                className="button delete-button"
                onClick={() => handleDeleteTodo(index)}
              >
                Delete
              </button>
            </div>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;
  1. 查看更改效果:保存文件时,开发服务器将自动重新加载应用程序,并在浏览器中显示最新的更改。通过在浏览器中查看http://localhost:3000,能够看到React应用程序更改的效果,此案例中可以完成增加、删除和编辑待办事项的动作。

屏幕截图 2023-08-12 110300.png

最终效果如图所示,虽然看着很简单,但是我真的花了不少时间,以此记录自己的学习过程。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
好的,下面是一个简单的日历和待办事项表的 React 组件的实现: ```javascript import React, { useState } from 'react'; const Calendar = () => { const [date, setDate] = useState(new Date()); const daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; const monthsOfYear = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; const month = date.getMonth(); const year = date.getFullYear(); const firstDayOfMonth = new Date(year, month, 1).getDay(); const daysInMonth = new Date(year, month + 1, 0).getDate(); const prevMonth = () => setDate(new Date(year, month - 1, 1)); const nextMonth = () => setDate(new Date(year, month + 1, 1)); return ( <div className="calendar"> <div className="calendar-header"> <button onClick={prevMonth}><</button> <h2>{monthsOfYear[month]} {year}</h2> <button onClick={nextMonth}>></button> </div> <table className="calendar-table"> <thead> <tr> {daysOfWeek.map(day => ( <th key={day}>{day}</th> ))} </tr> </thead> <tbody> {[...Array(Math.ceil((firstDayOfMonth + daysInMonth) / 7)).keys()].map(week => ( <tr key={week}> {[...Array(7).keys()].map(day => { const dateOfMonth = week * 7 + day + 1 - firstDayOfMonth; return ( <td key={day}> {dateOfMonth > 0 && dateOfMonth <= daysInMonth && dateOfMonth} </td> ); })} </tr> ))} </tbody> </table> </div> ); }; const TodoList = () => { const [todos, setTodos] = useState([]); const [inputValue, setInputValue] = useState(''); const handleInput = e => setInputValue(e.target.value); const handleSubmit = e => { e.preventDefault(); if (inputValue.trim() !== '') { setTodos([...todos, inputValue.trim()]); setInputValue(''); } }; const handleDelete = i => { setTodos([...todos.slice(0, i), ...todos.slice(i + 1)]); }; return ( <div className="todo-list"> <form onSubmit={handleSubmit}> <input type="text" value={inputValue} onChange={handleInput} /> <button type="submit">Add</button> </form> <ul> {todos.map((todo, i) => ( <li key={i}> {todo} <button onClick={() => handleDelete(i)}>×</button> </li> ))} </ul> </div> ); }; const App = () => ( <div> <Calendar /> <TodoList /> </div> ); export default App; ``` 这个组件中包含了一个简单的日历和一个待办事项列表,你可以在 `Calendar` 组件中修改一些细节,例如添加一些交互性和样式来更好地适应你的需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值