美文网首页
react版todolist详解

react版todolist详解

作者: 楠楠_c811 | 来源:发表于2019-03-25 11:58 被阅读0次

    这是个拆分了组件的todolist,只实现了增加和删除两个功能,可以着重理解一下子父组件之间的数据传递。

    // 当前组件是父组件
    import React, {Component} from 'react'
    // 引入子组件
    import TodoItem from './todoitem'
    
    class TodoList extends Component {
      // 初始构造函数
      constructor(props){
        super(props)
        // 定义初始数据
        this.state = ({
          list: [],
          inputValue: ''
        })
      }
      // 点击按钮方法
      handeBtnClick(){
        this.setState ({
          list: [...this.state.list,this.state.inputValue],
          inputValue: ''
        })
      }
      // 获取当前input值方法
      handeInputValue(e){
        this.setState({
          inputValue: e.target.value
        })
      }
      // 删除的方法
      handeDelete(index){
        // 复制一份数据出来操作,不要直接修改原数组
        const list = [...this.state.list];
        // 调用数组的方法 从当前下标删除一项
        list.splice(index,1)
        this.setState ({
          list:list
        })
      }
    
      render(){
        return(
          <div>
            <input value={this.state.inputValue} onChange={this.handeInputValue.bind(this)}/>
            <button onClick={this.handeBtnClick.bind(this)}>add</button>
            <ul>
              {
                this.state.list.map((item,index)=>{
                  // 父组件通过属性的形式向子组件传递参数
                  return <TodoItem key={index} index={index} content={item} delete={this.handeDelete.bind(this)} />
                  // return <li onClick={this.handeDelete.bind(this)} key={index}>{item}</li>
                })
              }
            </ul>
          </div>
        )
      }
    }
    export default TodoList;
    
    
    // 当前为子组件
    import React,{ Component } from 'react'
    // 子组件通过props接受父组件传递过来的参数
    class TodoItem extends Component{
        handeDeletr(){
            // 子组件要和父组件通信,需要调用父组件传递过来的方法  delete
            this.props.delete(this.props.index)
        }
        render(){
            return(
                  // 绑定点击事件,用以获取当前点击的下标,处理删除事件 
                <div onClick={this.handeDeletr.bind(this)}>
                  // 展示父组件传递过来的参数
                    {this.props.content}
                </div>
            )
        }
    }
    
    export default TodoItem;
    
    

    相关文章

      网友评论

          本文标题:react版todolist详解

          本文链接:https://www.haomeiwen.com/subject/icjvvqtx.html