import React,{Component} from 'react';
class TodosList extends Component{
constructor(){
super();
this.repaint = this.repaint.bind(this);
this.state = {
todos:[]
}
}
repaint(row){
this.setState({
todos:row
});
}
render(){
return (
<div className="todo-content">
<h1>TodoList</h1>
<AddNew todos = {this.state.todos} onAdd={this.repaint}/>
<ListTodo todos = {this.state.todos} onDelete={this.repaint}/>
</div>
);
}
}
class AddNew extends Component{
constructor(props){
super(props);
this.addTodo = this.addTodo.bind(this);
this.handleChange = this.handleChange.bind(this);
this.enter = this.enter.bind(this);
this.state = {
value:''
}
}
addTodo(){
if(this.state.value == ''){
alert('输入不能为空');
}else{
var row = this.props.todos;
row.push(this.state.value);
this.props.onAdd(row);
}
}
handleChange(e){
this.setState({
value:e.target.value
});
}
enter(e){
if(e.keyCode == 13){
this.addTodo(e);
e.target.value = '';
}
}
render(){
return (
<div>
<input type="text" onChange={this.handleChange} onKeyDown={this.enter}/>
<button id = 'find' onClick = {this.addTodo}>Add a task</button>
</div>
);
}
}
class ListTodo extends Component{
constructor(props){
super(props);
this.deleteTodo = this.deleteTodo.bind(this);
}
deleteTodo(e){
var index = e.target.getAttribute('data-key');
var row = this.props.todos;
row.splice(index,1);
this.props.onDelete(row);
}
render(){
return (
<ol>
{
this.props.todos.map(function(item,i){
return (
<li>
<span>{item}</span>
<button className="delete" onClick = {this.deleteTodo} data-key = {i}>×</button>
</li>
)
}.bind(this))
}
</ol>
);
}
}
export default TodosList;
网友评论