import React, { Component } from 'react';
import { Checkbox } from 'antd';
class TodoList extends Component {
constructor(props) {
super(props);
this.state = {
list: [
]
};
}
addData = () => {
var tempList = this.state.list;
tempList.push(
{
title: this.refs.title.value,
checked: false
}
);
// 添加完后回复空
this.refs.title.value = '';
this.setState({
list: tempList
})
// 缓存
localStorage.setItem("todoList", JSON.stringify(tempList));
}
removeData = (key) => {
var tempList = this.state.list;
tempList.splice(key, 1);
this.setState({
list: tempList
})
localStorage.setItem("todoList", JSON.stringify(tempList));
}
inputChange = (e) => {
if (e.keyCode == 13) {
this.addData();
}
}
handleCheck = (key) => {
var tempList = this.state.list;
tempList[key].checked = !tempList[key].checked;
this.setState({
list: tempList
})
localStorage.setItem("todoList", JSON.stringify(tempList));
}
//生命周期函数
componentDidMount() {
var todoList = JSON.parse(localStorage.getItem("todoList"));
if (todoList) {
this.setState({
list: todoList
})
}
}
render() {
return <div>
<input ref="title" onKeyUp={this.inputChange} /><button onClick={this.addData}>增加+</button>
<hr />
<h2>待办事项</h2>
<ul>
{
this.state.list.map((value, key) => {
if (!value.checked) {
return (
<li key={key}>
<input type="checkbox" checked={value.checked} onClick={this.handleCheck.bind(this, key)} />
{value.title}
<button onClick={this.removeData.bind(this, key)}>删除-</button>
</li>)
}
})
}
</ul>
<hr />
<h2>已完成事项</h2>
<ul>
{
this.state.list.map((value, key) => {
if (value.checked) {
return (
<li key={key}>
<input type="checkbox" checked={value.checked} onClick={this.handleCheck.bind(this, key)} />
{value.title} ----
<button onClick={this.removeData.bind(this, key)}>删除-</button>
</li>)
}
})
}
</ul>
</div>
}
}
export default TodoList;
React学习7.todoList的实现及数据缓存实现
最新推荐文章于 2024-04-24 09:46:49 发布