React學習之旅----Todolist
阿新 • • 發佈:2018-11-10
import React from 'react'; class TodoList2 extends React.Component { constructor(props) { super(props) this.state = { list: [ { title: '錄製ionic', checked: true }, { title: '錄製nodejs', checked: false } , { title: '錄製egg.js', checked: true }, { title: '錄製vue', checked: false } ], name: 'TodoList2' } } addData = (e) => { console.log(e) if (e.keyCode === 13) { let title = this.refs.title.value; let tempList = this.state.list; tempList.push({ title: title, checked: false }) this.setState({ list: tempList }) //表單置為空 this.refs.title.value = ''; } } delData = (key) => { var temList = this.state.list temList.splice(key, 1) this.setState({ list: temList }) } checkData = (key) => { let tempList = this.state.list; tempList[key].checked = !tempList[key].checked; this.setState({ list: tempList }) } render () { return ( <div> {this.state.name} <br /> <input ref='title' onKeyUp={this.addData} /> <h2>待辦事項</h2> <ul> { this.state.list.map((value, key) => { if (!value.checked) { return ( <li key={key}> <input type='checkbox' checked={value.checked} onChange={this.checkData.bind(this, key)} />{value.title}-----------<button onClick={this.delData.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.checkData.bind(this, key)} />{value.title}-----------<button onClick={this.delData.bind(this, key)}>刪除</button></li> ) } }) } </ul> </div> ) } } export default TodoList2;