App.js
import React, { Component, createRef } from "react";
import "./App.css";
class App extends Component {
constructor(props) {
super(props);
this.state = {
list: [
{ title: "vue", done: false },
{ title: "react", done: false },
],
};
// 创建一个dom引用
this.tempRef = createRef();
}
// 本地存储
componentDidMount() {
//获取本地存储的数据的数据 取不到用“[]”
var str = localStorage.getItem("list") || "[]";
//转成js对象
var list = JSON.parse(str);
//更新list
this.setState({ list });
}
componentDidUpdate(prevProps, prevState) {
//当数据更新的时候,把数据转换为字符串存储
localStorage.setItem("list", JSON.stringify(this.state.list));
}
// 删除
delItem = (item) => {
// 缓存list
var list = this.state.list;
// 查找下标
var ind = list.findIndex((value) => value.title == item.title);
// 删除所点击行
list.splice(ind, 1);
// 更新list数据
this.setState({ list });
};
// 添加
addItem = () => {
var list = this.state.list;
// 添加内容
list.unshift({ title: this.tempRef.current.value, done: false });
// 更新视图
this.setState({ list });
// 清楚input框内的内容
this.tempRef.current.value = "";
};
checkItem = (item) => {
var list = this.state.list;
// 查找下表
var ind = list.findIndex((value) => value.title == item.title);
// 值取反
list[ind].done = !list[ind].done;
// 更新视图
this.setState({ list });
};
render() {
return (
<div className="con">
<div className="cen">
<input type="text" ref={this.tempRef} className="inp" />
<button onClick={this.addItem} className="btn1">
添加
</button>
</div>
<h3>正在进行 {this.state.list.filter((item) => !item.done).length}</h3>
{this.state.list
.filter((item) => !item.done)
.map((item) => (
<div className="item" key={item.title}>
<label>
<input
type="checkbox"
checked={item.done}
onChange={this.checkItem.bind(this, item)}
/>
<span className="span">{item.title}</span>
</label>
{/* 删除功能 */}
<button className="btn2" onClick={this.delItem.bind(this, item)}>
x
</button>
</div>
))}
<h3>已完成 {this.state.list.filter((item) => item.done).length}</h3>
{this.state.list
.filter((item) => item.done)
.map((item) => (
<div className="item" key={item.title}>
<label>
<input
type="checkbox"
checked={item.done}
onChange={this.checkItem.bind(this, item)}
/>
<span className="span">{item.title}</span>
</label>
{/* 删除功能 */}
<button className="btn2" onClick={this.delItem.bind(this, item)}>
x
</button>
</div>
))}
</div>
);
}
}
export default App;
App.css
.con {
overflow: hidden;
width: 500px;
min-height: 400px;
background-color: #ccc;
margin: 0 auto;
}
.inp {
line-height: 25px;
font-size: 18px;
}
.cen {
text-align: center;
margin: 15px 0;
}
.btn1 {
border: none;
margin-left: 7px;
background-color: #f4f4f4;
padding: 4px 11px;
font-size: 15px;
border-radius: 5px;
}
.item {
margin-bottom: 10px;
clear: both;
font-size: 18px;
margin-left: 20px;
}
.btn2 {
float: right;
margin-right: 60px;
}
.span {
font-size: 20px;
}
h3{
padding-left: 10px;
}
如下图