使用react开发一个简单的todo_list

本文详细介绍了如何使用React和hooks(useState)实现一个基础的待办事项列表应用,包括TodoForm用于添加任务,以及Todo组件展示、完成和删除功能。
摘要由CSDN通过智能技术生成
import React, { useState } from 'react';
import './App.css';

function TodoForm({addTodo}) {
  const [value, setValue] = useState('');
  const handleSubmit = e => {
    e.preventDefault();
    if(!value) return;
    addTodo(value);
    setValue('');
  }
  return <form onSubmit={handleSubmit}>
    <input type='text' placeholder='add todo...' value={value} onChange={e=>setValue(e.target.value)}></input>
  </form>
}

function Todo({todo, index, finishTodo, removeTodo}){
  const handleComplete = e => {
    finishTodo(index);
  }

  const handleDelete = e => {
    removeTodo(index);
  }

  return (
    <div style={{textDecoration: todo.isComplete?'line-through':''}}>
      <div>
          {todo.text}
          <button onClick={handleComplete}>完成</button>
          <button onClick={handleDelete}>删除</button>
      </div>
    </div>
  )
}

function App() {
  const [todos,setTodo] = useState([
    {text: 'sleep', isComplete: false},
    {text: 'eat', isComplete: true}
  ])

  const addTodo = text => {
    const todo = {text: text}
    const newTodos = [...todos, todo];
    setTodo(newTodos);
  }

  const finishTodo = index => {
    const newTodos = [...todos];
    newTodos[index].isComplete = true;
    setTodo(newTodos);
  }

  const removeTodo = index => {
    const newTodos = [...todos];
    newTodos.splice(index, 1);
    setTodo(newTodos);
  }
  
  return (
    <div className="App">
      <h1>todos</h1>
      <div>
        {
          todos.map((todo, index) => {
            return <Todo todo={todo} index={index} key={index} finishTodo={finishTodo} removeTodo={removeTodo}></Todo>
          })
        }
      </div>
      <TodoForm addTodo={addTodo}></TodoForm>
    </div>
  );
}

export default App;


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值