import { React,Component } from 'react'
import './todos.css'
class Todos extends Component {
state = {
inputValue :'',
todos:[
{ title: 'learn React' , done:false ,id : Date.now() },
{ title: 'learn Vue' , done:false , id :Date.now()},
{ title: 'learn JS', done:false , id :Date.now()}
]
}
// 初始化生命周期函数
componentWillMount() {
console.log(this.state.todos , 15);
let a = JSON.parse(window.localStorage.getItem('todos'))
if( a ) {
this.setState({
todos:a
})
}
// 强制刷新
this.forceUpdate()
}
// 获取input 中的内容
handInp = evt => {
this.setState ({
inputValue : evt.target.value.trim() ,
})
// console.log( evt.target.value);
}
// 提交
onEnter = evt => {
// 按回车键提交
if ( 13 === evt.keyCode && evt.target.value.trim() !== '') {
console.log(this.state.todos , 49);
let Ao = []
Ao = this.state.todos
Ao.push({
title:evt.target.value.trim() ,
done:false ,
id : Date.now()
})
this.setState({
todos:Ao
})
console.log('this.state.todos' , this.state.todos);
this.setState({
inputValue : ''
})
// 存到local storage 中
window.localStorage.setItem('todos',JSON.stringify(this.state.todos) )
this.forceUpdate()
}
}
// 删除按钮
delFn = (index ,evt) => {
this.state.todos.splice(index, 1)
let add = JSON.parse(window.localStorage.getItem('todos'))
console.log(evt.target.parentNode);
// 找到相同的id 然后把他截取 findindex 返回的是索引位置
add.splice(add.findIndex( item => item.id == evt.target.parentNode.dataset ) , 1)
window.localStorage.setItem('todos' , JSON.stringify(this.state.todos))
this.forceUpdate()
}
// 完成按钮
addFn = index => {
let finishTodos = this.state.todos
finishTodos[index].done = !finishTodos[index].done
this.setState({
todos:finishTodos
})
window.localStorage.setItem('todos' , JSON.stringify(this.state.todos))
this.forceUpdate()
}
cheekFn = () => {
alert(" Your are best ===== 宝贝 你是最棒的"
)
}
render() {
return (
<div>
要完成的目标 : <input type="text" onChange={ this.handInp }
onKeyUp={this.onEnter } value={this.state.inputValue} />
<ul>
<h3> 要做的目标 </h3>
{
(this.state.todos? this.state.todos:[]).map((item , index) => {
if (!item.done)
return (
<li key= {index} data-id={item.id}>
<button onClick={ () => this.addFn(index) }> finish 🉑 </button>
{item.title}
<button onClick={ (evt) => this.delFn (index ,evt) }> delete ❌ </button>
</li>
)
}
)
}
</ul>
<hr />
<ul className="finish">
<h3> 已完成的事情 </h3>
{
(this.state.todos? this.state.todos:[]).map( (item , index )=> {
if (item.done) {
return (
<li key={index} className="bb">
<button onClick= { (evt) => this.delFn (index , evt) }> end 👌 </button>
<h3> 完成的目标 </h3>
{item.title}
<button onClick={this.cheekFn} className="big"> That's great 🦾</button>
</li> )
}
}
)
}
</ul>
</div>
);
}
}
export default Todos;