老莫的笔记本  
  
查看: 832|回复: 0

一个简单的ToDoList

[复制链接]

662

主题

878

帖子

5145

积分

超级版主

Rank: 8Rank: 8

积分
5145
发表于 2019-12-19 11:14:14 | 显示全部楼层 |阅读模式
  1. import React, { Fragment, Component } from 'react';
  2. import './App.css';

  3. class Mytest extends Component {
  4.   // 第一步 在所有函数之前执行的函数
  5.   // 这是固定写法??? what  why

  6.   constructor(props) {

  7.     super(props);

  8.     // 所有的数据 都在 state里
  9.     this.state = {
  10.       inputValue: '',
  11.       list: []
  12.     }

  13.   }

  14.   render() {
  15.     return (
  16.       <Fragment>

  17.         <div className="Mytest">
  18.           <input
  19.             value={this.state.inputValue}
  20.             onChange={this.hand.bind(this)}
  21.             onKeyDown ={this.handleKey.bind(this)}
  22.             // 这里的 bind(this) 表示在该函数中重新制定该this对象 为 类本身
  23.             type="text" />
  24.           <button  onClick={this.handleBtnClick.bind(this) }   >提交</button>
  25.         </div>
  26.         <ul>
  27.           {
  28.             this.state.list.map((item, index) => {
  29.               // 如果此处不加 key 值 控制台会给警告: 列表中每个内容都得有个独特的key
  30.               // 这里这个 bind 里,绑定this  还可以传递一个索引值 index
  31.               return (
  32.                 <li key = {index} onClick={this.handleLiClick.bind(this,index)}>
  33.                    {item}
  34.                 </li>
  35.               );
  36.             })
  37.           }

  38.         </ul>
  39.       </Fragment>

  40.     );
  41.   }

  42.   hand(e) {
  43.     // 默认接受事件对象 e  ,
  44.     // e.target 为所操作的Dom
  45.     // e.target.value 为所操作的value 值
  46.     console.log(e.target.value)

  47.     // this.state.inputValue =e.target.value;错误写法
  48.     // 直接指定this.state 的值 并不能 改变其value的值 ,需要通过this.setState()
  49.     this.setState({
  50.       inputValue: e.target.value
  51.     })

  52.   }
  53.   // 回车事件,我自己瞎几把测的
  54.   handleKey(e)
  55.   {
  56.     // console.log(e.keyCode)
  57.     //
  58.     if(e.keyCode==13)
  59.     {
  60.       this.handleBtnClick();
  61.     }
  62.   }

  63.   // 提交事件
  64.   handleBtnClick()
  65.   {
  66.      this.setState({
  67.        list:[...this.state.list,this.state.inputValue],
  68.        inputValue:''
  69.      })
  70.      // 这里 虽然视频没讲 ,但是有一个逻辑顺序在里面 就是 从上往下  ,才能实现input 的清空
  71.   }



  72.   // 删除事件
  73.   handleLiClick(index)
  74.   {
  75.     let listCopy = [...this.state.list];
  76.     listCopy.splice(index,1);
  77.     // 为什么要先复制一份数组呢, 是因为react 有个Immutable 规定 [ 就是在创建新数据时 要保证旧数据仍然可用的规定  ]
  78.     // Immutable 参考地址 https://www.cnblogs.com/chris-oil/p/8494337.html  

  79.     this.setState({
  80.        list:listCopy
  81.     })

  82.   }



  83. }

  84. export default Mytest;
复制代码


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表