码迷,mamicode.com
首页 > 其他好文 > 详细

react TodoList

时间:2020-02-18 13:22:19      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:ffline   onchange   set   some   width   onclick   mamicode   document   info   

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

标签:ffline   onchange   set   some   width   onclick   mamicode   document   info   

原文地址:https://www.cnblogs.com/zlrrrr/p/12325517.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!