TodoList


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}>&times;</button>
                            </li>

                        )
                    }.bind(this))
                }
            </ol>
        );
    }
}
export default TodosList;
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容