加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

(二)todolist 练习

发布时间:2020-12-15 20:37:12 所属栏目:百科 来源:网络整理
导读://拆分组件结构,编写静态组件,编写动态组件,组件交互 //组件传值,子组件如何更改父组件的状态,在父组件重定义方法传递给子组件 class App extends React.Component{ constructor(props){ super(props) this.state = { todos:["吃饭","睡觉","打豆豆"] }
    //拆分组件结构,编写静态组件,编写动态组件,组件交互
    //组件传值,子组件如何更改父组件的状态,在父组件重定义方法传递给子组件
    class App extends React.Component{
        constructor(props){
            super(props)
            this.state = {
                todos:["吃饭","睡觉","打豆豆"]
            }
            this.Addtodo = this.Addtodo.bind(this)
        }

        //添加todo
        Addtodo(todo){
          const todos = this.state.todos
            todos.unshift(todo)
            this.setState({
                todos
            })

        }

        render(){
            return (
                <div>
                    <h1>Simple TODO List</h1>
                    <Add Addtodo={this.Addtodo} todos={this.state.todos}/>
                    <List todos={this.state.todos}/>
                </div>
            )
        }
    }

    class Add extends React.Component{

        constructor(props){
            super(props)
            this.HandleClick = this.HandleClick.bind(this)
        }

        HandleClick(){
            //在父组件中添加数据
            const todo =  this.Todoinput.value.trim()  //检验

            if(!todo){
                return
            }

            //调用父类的方法
            this.props.Addtodo(todo);
            //清空输入框
            this.Todoinput.value = "";
        }


        render(){
            return(
                <div>
                    <input ref={input => this.Todoinput = input} type="text"/>
                    <button onClick={this.HandleClick}>Add #{this.props.todos.length+1}</button>
                </div>
            )
        }
    }
    Add.propTypes = {
        todos : PropTypes.array.isRequired,Addtodo :PropTypes.func.isRequired
    }

    class List extends React.Component{
        render(){
             return (
                 <ul>
                     {this.props.todos.map((todo,index)=>{
                        return (<li key={index}>{todo}</li>)
                     })}
                 </ul>
             )
        }
    }
  //参数必须传递,并且是一个数组
    List.propTypes = {
        todos : PropTypes.array.isRequired
    }

  ReactDOM.render(<App/>,document.getElementById("example"))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读