当前位置: 移动技术网 > IT编程>脚本编程>编辑器 > 详解React中的todo-list

详解React中的todo-list

2019年05月28日  | 移动技术网IT编程  | 我要评论

基于react的一个简单todo-list

先赌为快:在线demo,感觉还不错点一下star  -_- ~

源码地址

一、已经完成的功能

1、新增选项(默认未完成)

2、完成状态可以切换

3、当前选项可以删除

4、全部选项选中状态切换

5、全部个数,完成个数,未完成个数实时读取

6、刷新状态不变

7、双击可以编辑(有个坑:双击编辑内input的keyup enter保存会连带触发blur失去焦点保存。已解决:通过设置一个可以保存的状态控制)

二、待完成(新增路由)

三、目录结构

3.1、主要逻辑只涉及:todo(父组件),todoadd(输入框子组件一),todolist(选项列表子组件二)

3.2、父子组件通过props(可以是自定义属性、对象、回调函数)通信,每个组件都有自己的state,可以通过setstate改变当前的state。

例如:新增的时候,父组件是如何知道新增了一个什么内容呢?如下:

// todo.jsx内   
//1 传递给子组件的回调函数,只要有心得内容传递过来,就更新当前的:list。list只要更新,通过props传递给todolist的data就会更新,dom就会新增一个选项列表
  onaddsubmit(addtitle) {
    console.log("增加了:" + addtitle)
    let additem = {
      title: addtitle,
      isfinished: false
    }
    this.state.list.unshift(additem)
    this.setstate({ list: this.state.list })
    this._savetosession()
  }
// 通过props传递给子组件(等待使用)
<todoadd onaddsubmit={this.onaddsubmit} />

// todoadd.jsx
// 2、點擊enter鍵:有值就確認增加
  _onkeyupenter(e) {
    if (e.keycode == 13) {
      this.confirmadditem()
    }
  }
  // 3、失去焦點:有值就確認增加
  _onblurenter(e) {
    this.confirmadditem()
  }
  // 4、確認增加,调用父组件的回调函数,传递参数
  confirmadditem() {
    if (this.state.title) {
      this.props.onaddsubmit(this.state.title) //把新增的内容通过props传进来的回调函数告诉父组件todo,有新的内容来了
      // 置空當前
      this.setstate({
        title: ""
      })
    }
  }

其他:上面这个简单的父子组件的通信过程和es6模块化通信非常类似,只是react做了优化,比如上面的使用es6来模拟如下,只是做了通信模拟:

// todo.js 父模块
import todoadd from "./todoadd"
import todolist from "./todolist"
class todo {
  constructor() {
    this.list = []
    this.todoadd = new todoadd({
      // 父模块给子模块的回调
      resetlist: (content) => {
        if (content) {
          this._updatelist(content)
        }
      }
    })
    this.todolist = new todolist({
      list: this.list,
    })
  }
  _updatelist(content) {
    this.list.push(content)
    // 调用子模块的方法更新内部列表
    this.todolist && this.todolist._getnewlist(this.list)
  }
}
module.exports = todo

// todoadd.js 新增子模块
class todoadd {
  constructor({
    resetlist,
  }) {
    this.resetlist = resetlist
  }
  _onsubmit(str) {
    if (str) {
      // 1、告诉父模块新增了
      this.resetlist(str)
    }
  }
}
module.exports = todoadd

// todolist.js 列表子模块
class todolist {
  constructor({
    list,
  }) {
    this.list = []
    this._getnewlist(list)
  }
  // 3、监听父模块是否要更新
  _getnewlist(newlist) {
    this.list = newlist
    // 其他操作
  }
}
module.exports = todolist

以上所述是小编给大家介绍的react中的todo-list ,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网