react TodoList

Posted zlrrrr

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了react TodoList相关的知识,希望对你有一定的参考价值。

import React, {useState} from ‘react‘;

function TodoList() {
  const [list, setList] = useState([]);
  const [text, setText] = useState("");
  const [done, setDone] = useState(["thing1", "thing2"]);

  function Add() {
    let arr = [];
    arr = [...list, text];
    setList(arr);
    setText("");
  }

  function deletee( e) {
    let ind = list.indexOf(e) ;
    let arr;
    let dones = [...done, list[ind]];
    console.log(dones);
    if (ind === 0) {
      arr = list.slice(1);
    } else if (ind === list.length - 1) {
      arr = list.slice(0, list.length - 1);
    } else {
      let arr1 = list.slice(0, ind);
      let arr2 = list.slice(ind + 1);
      arr = [...arr1, ...arr2];
    }
    setList(arr);
    setDone(dones);
  }

  return (
    <>
      <div>
        <h3>TodoList</h3>
        <input id = "todo" onChange = {(e) => {setText(e.target.value)}} value={text}/>
        <button onClick = {Add} style = {{marginLeft: 10}} >ADD</button>
      </div>
      <ul>
        {list.map((val, index) => {
          return <li data-index = {index} key = {index}>{val}
            <button onClick = {() => deletee(val)} style = {{marginLeft: 10}}>x</button>
          </li>
        })}
      </ul>
      <div>
        <h3 style = {{color: ‘green‘}}>Done</h3>
        <ul>
        {done.map((val, index) => {
          return <li style = {{color: ‘green‘}} data-index = {index} key = {index}>{val}</li>
        })}
        </ul>
      </div>
    </>
  );
}

export default TodoList;
import React from ‘react‘;
import ReactDOM from ‘react-dom‘;
import ‘./index.css‘;
import * as serviceWorker from ‘./serviceWorker‘;
import TodoList from ‘./App‘;


ReactDOM.render(<TodoList />, document.getElementById(‘root‘));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

技术图片

 

 技术图片

 

利用 react 的 hook 写了一个简易的 todolist 实现简单的增加和删除功能 删除后的内容保存到下面 done 的列表中

 

以上是关于react TodoList的主要内容,如果未能解决你的问题,请参考以下文章

react todoList小demo

react——一个todolist的demo

React组件开发经典案例--todolist

初探react,用react实现一个todoList功能

初探react,用react实现一个todoList功能

react新手demo——TodoList