Todolist.js代码如下:
import React,{Component} from 'react';
import '../assets/css/index.css';
//引入自定义模块
import storage from '../model/Storage'
class Todolist extends Component{
constructor(props){
super(props);
this.state={
list:[
// {
// title:'录制a',
// checked:true
// },
// {
// title:'录制b',
// checked:false
// },
// {
// title:'录制c',
// checked:true
// },
// {
// title:'录制d',
// checked:false
// },
// {
// title:'录制e',
// checked:true
// },
]
}
}
addData=(e)=>{
//按下回车的时候再增加
if(e.keyCode==13){
//获取dom节点的数据
let title=this.refs.title.value;
let tempList=this.state.list;
tempList.push({
title:title,
checked:false
})
//改变后的值赋值给list
this.setState({
list:tempList
})
//表单置换为空
this.refs.title.value='';
//执行缓存数据
// localStorage.setItem('todolist',JSON.stringify(tempList));
storage.set('todolist',tempList);
}
}
checkboxChange=(key)=>{
let tempList=this.state.list;
tempList[key].checked=!tempList[key].checked;
//改完之后把值赋值给list
this.setState({
list:tempList
})
//执行缓存数据
// localStorage.setItem('todolist',JSON.stringify(tempList));
storage.set('todolist',tempList);
}
removeData=(key)=>{
let tempList=this.state.list;
tempList.splice(key,1);
//改完之后把值赋值给list
this.setState({
list:tempList
})
//执行缓存数据
// localStorage.setItem('todolist',JSON.stringify(tempList));
storage.set('todolist',tempList);
}
//生命周期函数
//一刷新就触发的方法
componentDidMount(){
//获取暖村的数据
// var todolist=JSON.parse(localStorage.getItem('todolist'));
var todolist=storage.get('todolist');
if(todolist){
this.setState({
list:todolist
})
}
}
render(){
return(
<div>
//设置一个鼠标按下的事件
<header className="title"> Todolist <input ref="title" onKeyUp={this.addData} /> </header>
<h2>待办事项</h2>
<hr/>
<ul>
{
this.state.list.map((value,key)=>{
if(!value.checked){
return(
<li key={key}>
<input type="checkbox" checked={value.checked} onChange={this.checkboxChange.bind(this,key)}/>
{value.title}
<button onClick={this.removeData.bind(this,key)}>删除</button>
</li>
)
}
})
}
</ul>
<h2>已完成事项</h2>
<hr/>
{
this.state.list.map((value,key)=>{
if(value.checked){
return(
<li key={key}>
<input type="checkbox" checked={value.checked} onChange={this.checkboxChange.bind(this,key)}/>
{value.title}
<button onClick={this.removeData.bind(this,key)}>删除</button>
</li>
)
}
})
}
</div>
)
}
}
export default Todolist;
Storage.js封装缓存数据代码如下:
var Storage={
set(key,value){
localStorage.setItem(key,JSON.stringify(value));
},
get(key){
return JSON.parse(localStorage.getItem(key));
},
remove(key){
localStorage.removeItem(key);
},
}
export default Storage;
注意本次使用了生命周期函数
//生命周期函数
//一刷新就触发的方法
componentDidMount(){
效果如下所示: