import React, { Component } from 'react'
import "./index.css"
export default class ToDolistThree extends Component {
state = {
list: [
{ id: 1, name: "HTML", status: "done" },
{ id: 2, name: "JAVA", status: "undone" },
{ id: 3, name: "JAVASCRIPT", status: "done" }
],
param: "All"
}
add = () => {
const val = this.myinput.value
const { list } = this.state
const t = { id: list.length, name: val, status: "undone" }
list.push(t)
this.setState({ list })
console.log(list.length);
}
toggle = (e) => {
const { list } = this.state
const id = e.target.getAttribute("data-id")
for (let obj of list) {
if (obj.id === Number(id)) {
obj.status = obj.status === "done" ? "undone" : "done"
break
}
}
this.setState({ list })
}
toggleBtn = (e) => {
const param = e.target.getAttribute("data-item")
this.setState({ param })
}
total() {
const { list, param } = this.state
switch (param) {
case "Active": return list.filter(item => item.status === "done")
case "Done": return list.filter(item => item.status === "undone")
default: return list
}
}
render() {
const { param } = this.state
return (
<div>
<div>
<input ref={node => this.myinput = node} type="text" /><button onClick={this.add}>添加</button>
</div>
<div>
<ul onClick={this.toggle}>
{this.total().map(item => {
return <li data-id={item.id} key={item.id} className={item.status}>{item.name}</li>
})}
</ul>
</div>
<div onClick={this.toggleBtn}>
<button data-item="All" className={param === "All" ? "data" : ""}>全部完成</button>
<button data-item="Active" className={param === "Active" ? "data" : ""}>已完成</button>
<button data-item="Done" className={param === "Done" ? "data" : ""}>未完成</button>
</div>
</div>
)
}
}
css
.undone{
color: black;
}
.done{
color: red;
text-decoration: line-through;
}
.data{
color: white;
background-color: red;
}
可能不是特完善,尽请谅解!