import React, { Component } from 'react'; import '../assets/css/TodoList.css' class TodoList extends Component { constructor(prors) { super(prors); this.state = { // 数据 list: [ { title: '吃苹果', checked: true }, { title: '吃草莓', checked: false }, { title: '吃栗子', checked: true } ] } } render() { return ( <div> {/* 回车添加数据 */} <input type="text" ref="title" onKeyUp={this.addData}></input> <hr></hr> <h2>代办事项</h2> <ul> { this.state.list.map((value, key) => { if (!value.checked) { return ( <li key={key}> <input type="checkbox" checked={value.checked} onChange={this.checkedChage.bind(this, key, value.checked)} /> {value.title} <button onClick={this.removeData.bind(this, key)}>删除</button> </li> ) } }) } </ul> <h2>已完成事项</h2> <ul> { this.state.list.map((value, key) => { if (value.checked) { return ( <li key={key}> <input type="checkbox" checked={value.checked} onChange={this.checkedChage.bind(this, key, value.checked)} /> {value.title} <button onClick={this.removeData.bind(this, key)}>删除</button> </li> ) } }) } </ul> </div> ) } // 注意写错箭头参数 this指向问题 // 输入弹起 addData = (e) => { // 按下回车的时候赋值 if (e.keyCode === 13) { let tempList = this.state.list; if (this.refs.title.value !== '' && this.refs.title.value !== undefined) { tempList.push({ title: this.refs.title.value, checked: false }); // 获取表单的值赋值 this.refs.title.value = ''; // 输入框赋值为空 this.setState({ // 赋值到list list: tempList }) } } } // 删除 removeData = (key) => { let tempList = this.state.list; tempList.splice(key, 1); this.setState({ list: tempList }) } // checked选中调用 checkedChage(key, val) { let tempList = this.state.list; tempList[key].checked = !tempList[key].checked // checked状态取反 this.setState({ // 赋值到list list: tempList }) } } export default TodoList
本文作者为gengboxb,转载请注明。