首页 > 技术文章 > ToDoList

pan-pan309 2019-12-25 08:29 原文

1.引入所需要的组件,antd,ant Design的css还有所需要的组件

2.增删改

import React, { Component } from 'react'
import { Input,Button } from 'antd';
import "antd/dist/antd.css"
import ListItem from './ListItem';

export default class Home extends Component {
  constructor(props){
    super()
    this.state={
      inputValue:"",
      item:[1,2,3,4]
    }
  }
  render() {
    return (
      <div>
        <Input onChange={this.inputChange.bind(this)} 
               value={this.state.inputValue}
        />
        <Button type="primary" onClick={this.addItem.bind(this)}>添加</Button>
        <div>
          {
            this.state.item.map((value,index)=>{
              return(
                <div key={index}>
                    <ListItem content={value}
                    index={index}
                    // 调用父组件的方法传给子组件
                    deleteItem={this.deleteItem.bind(this)}/>
                </div>
              )
            })
          }
        </div>
      </div>
    )
  }
  // input框的方法
  inputChange(e){
    this.setState({
      inputValue:e.target.value
    })
  }
  // 增加列表
  addItem(){
    this.setState({
      item:[...this.state.item,this.state.inputValue],
      inputValue:""
    })
  }
  // 删除列表
  deleteItem(index){
    // 检测是否能打印出索引
    // console.log(index)
    let item = this.state.item;
    item.splice(index,1);
    this.setState({
      item:item
    })
  }
  // 这个是坑,性能会受到影响,基本不会发现有问题,如果做大项目传值就会有问题
  // deleteItem(index){
  //   this.state.item.splice(index,1);
  //   this.setState({
  //     item:this.state.item
  //   })
  // }
}

推荐阅读