用react做输入TODOS自动添加列表

适用于React初学者实现一个从输入框输入内容,自动添加列表的小案例


一般的TODOlist事项列表功能都是添加事项,完成事项,删除事项,查看分类事项,

我们暂时分类按照待完成事项和已完成事项,按照一个一个功能模块来完成,更加轻易上手


一、配置环境,建立一个index.js

搭建react环境,跑通环境

import React from 'react';

import ReactDOM from 'react-dom';

import Todo from './todo';

ReactDOM.render(,document.getElementById('root'));


二、建立todo.js父组件

先实现简单的添加功能,通过form表单实现


class Todo extends React.Component { 

 constructor(props){  

   super(); 

    this.state={      items:[],      text:''    }

  } ;

 handleSubmit(e){   

        e.preventDefault();

       let newItem = this.refs.input.value.trim();  

       this.refs.input.value=null  //清空内容   

       if (newItem==''&& !newItem) {      

             this.refs.input.focus();   

     return alert('不能为空')   

        }  //排除空值 

         this.state.items.push(newItem)  //将输入的内容  

         this.setState({  items:this.state.items  }) 

  }

 render () {    

     return(

       <div>

           <h1> Todo<h1> 

        <form onSubmit={this.handleSubmit.bind(this)}>

              <input  type="text" placeholder='add a todo' />

              <button>add#{this.state.items.length+1}</button>

          </form>

      </div>


       )

  }

}

export default Todo;

三、简单的todolist.js子组件


实现简单的添加功能.props将父组件定义的数组items传过来,用es6的map遍历传递数组


export default class TodoList extends Component { 

 render() {   

 let list = this.props.items.map( (item,index) =>

       <div key={index}>{item}</div>)   

   return (

     <div>{list}</div>

); 

}}

四.扩展删除功能


添加 todo.js 一个删除的方法

handleDel(i){

   this.state.items.splice(index,1)

   this.setState({

       items:this.state.items

  })

}

添加到 todolist.js  中button组件按钮


let list = this.props.items.map( (item,index) =>

<div key={index}>

{item.title}

<button onClick={this.handleDelete.bind(this,index)}}>delete</button>

</div>


五.添加完成事项功能

添加已完成事项选中的功能,用radio实现。

通过设置传入的item.completed 的true 或者false的值处理判断是否选中

添加方法

handleComponent(){

this.state.items[index].completed=!this.state.items[index].completed

this.setState({

items:this.state.items

})}

如下代码通过map将item 传入一个div中

let list = this.props.items.map( (item,index) =>      

<div key="index">

<input type = "radio"  checked={item.completed}  onChange={this.handleChange.bind(this,index)} />

<span style={item.completed ? {textDecoration: "line-through",color:'#ccc'} : null}>{item.title}</span>

<button onClick={this.handleDelete.bind(this,index)}>删除</button>

</div>

)


从todo.js传入删除方法和完成事项方法到todolist.js中

handleChange(i){

//传入一个方法,必须加i,传入的形参

this.props.handleComponent(i)

}

handleDelete(i){

this.props.handleDel(i)

}

todo.js组件添加初始设定

constructor(props){

super();

this.state={

items:[

{title:'aa',completed:false},

{title:'bb',completed:true}//用completed的布尔值判断事项是否已完成

],

show:0}}

六、实现分类查看功能

我们分为待办事项和已完成事项,查看就可以查看全部事项,待办事项,已完成事项

首先我们定义添加三个按钮组件,"All","Active","Completed"

let name = ["All","Active","Completed"];                  

let button = name.map( (item,index) =>

<button key={index} onClick={this.handleShow.bind(this,index)}

style = {this.state.show == index ? {backgroundColor:'#00bcd4'} : null}>{items}

</button>


在render中添加判断状态,0为all状态,1为Active  2为Completed

if (this.state.show==0) {

var showItems=this.state.items;

}else if (this.state.show==1) {

var showItems=this.state.items.filter(function (element) {

return element.completed== false

})

}else {

var showItems=this.state.items.filter(function (element) {

return element.completed== true

})//`add# ${this.items.length+1}`

};

添加 handleShow功能

handleShow(i){

this.setState({show:i})

}

OK,现在一个事项添加几乎完成了,但是功能还不够完善,因为index值在分类查看时会出现问题,所以用id传值更加严谨,后续改善功能代码如下

完整的todo.js代码

class Todo extends React.Component { 

 constructor(props){ 

   super(); 

   this.state={ 

      items:[     

         {title:'aa',completed:false,id:1},     

         {title:'bb',completed:true,id:2}   

    ],     

      show:0    }  } 

 handleSubmit(e){ 

     e.preventDefault();   

     let inputValue = this.refs.input.value.trim(); 

     this.refs.input.value=null //清空内容 

     if (inputValue==''&& !inputValue) {   

           this.refs.input.focus();   

            return alert('不能为空')    } //排除空值 

     let date = new Date; 

    let newItem={title:inputValue,completed:false,id:date.getTime()}   

    this.state.items.push(newItem) //将输入的内容   

     this.setState({  items:this.state.items  }) 

   } 

 handleComponent(id){ 

     var index = this.state.items.findIndex(function(ele){ 

           return id == ele.id    })  

     this.state.items[index].completed=!this.state.items[index].completed  

   this.setState({      items:this.state.items    }) 

handleDel(id){   

    var index = this.state.items.findIndex(function(ele){ 

        return id == ele.id 

   })   

  this.state.items.splice(index,1) 

  this.setState({      items:this.state.items    }) 

}

handleShow(id){ 

    this.setState({show:id}) 

 }

render () { 

   if (this.state.show==0) {     

   var showItems=this.state.items;   

 }else if (this.state.show==1) {     

 var showItems=this.state.items.filter(function (element) { 

      return element.completed== false     

})   

}else {   

   var showItems=this.state.items.filter(function (element) {     

          return element.completed== true      })

   };     

  let name = ["All","Active","Completed"];     

  let button = name.map( (item,index) =>{item})  return(

        <h1>Todo</h1>

        <TodoList items={showItems}

            handleComponent{this.handleComponent.bind(this)}

            handleDel={this.handleDel.bind(this)}/>

       <form onSubmit={this.handleSubmit.bind(this)}>

       <input placeholder='add a todo' ref="input"/>

      <button>add#{this.state.items.length+1}</button>

    {button}

  ) 

}}

export default Todo;

todolist.js代码如下

export default class TodoList extends Component {

handleChange(id){ 

 this.props.handleComponent(id)

}

handleDelete(id){

   this.props.handleDel(id)

render() {   

let list = this.props.items.map( item =>  

<div key={item.id} className="li">

<input type="radio" checked={item.completed} onChange=

{this.handleChange.bind(this,item.id)} />

<span style={item.completed ? {textDecoration: "line-through",color:'#999'} :

null}>{item.title}</span>

<buttononClick={this.handleDelete.bind(this,item.id)} >删除</button>

)   

return (

<div>

{list}

</div>

);  }}

成功完成功能,后续样式可以自己修改了!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容