zoukankan      html  css  js  c++  java
  • react todolist

    import React, {Component} from 'react';
    
    class AddItem extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          value: ''
        };
        this.handleChange = this.handleChange.bind(this);
        this.handleClick = this.handleClick.bind(this);
      }
    
      handleChange(e) {
        this.setState({
          value: e.target.value
        });
      }
      handleClick() {
        this.props.handleAdd(this.state.value);
      }
      render() {
        return (
          <div>
            <input type='text' onChange={this.handleChange} />
            <button onClick={this.handleClick}>+</button>
          </div>
        );
      }
    }
    
    class ListItem extends React.Component {
      constructor(props) {
        super(props);
        this.handleDelete = this.handleDelete.bind(this);
      }
    
      handleDelete(e) {
        let index = e.target.dataset.index;
        this.props.handleDelete(index);
      }
      render() {
        let items = [];
        this.props.items.forEach((item, index) => {
          items.push(
            <div key={index}>
              <span>{item}</span>
              <button onClick={this.handleDelete} data-index={index}>x</button>
            </div>
          );
        });
        return (
          <div>
            {items}
          </div>
        );
      }
    }
    
    class TodoList extends React.Component {
    
      constructor(props) {
        super(props);
        this.state = {
          items: []
        }
        this.handleAdd = this.handleAdd.bind(this);
        this.handleDelete = this.handleDelete.bind(this);
      }
    
      handleAdd(value) {
        this.state.items.push(value);
        this.setState({
          items: this.state.items
        });
        console.log(this.state.items);
      }
    
      handleDelete(index) {
        this.state.items.splice(index,1);
        this.setState({
          items: this.state.items
        });
        console.log(this.state.items);
      }
    
      render() {
        return (
          <div>
            <AddItem handleAdd={this.handleAdd}/>
            <ListItem items={this.state.items} handleDelete={this.handleDelete}/>
          </div>
        );
      }
    }
    
    export default TodoList;
    
  • 相关阅读:
    TCP/IP 网路基础
    三、Django之请求与响应-Part 1
    二、Django快速安装
    Linux 优化详解
    缓存的正确使用方式
    HTML从入门到放弃
    Ansible开发之路
    程序猿数据库学习指南
    MySQL错误代码大全
    Python之网络编程
  • 原文地址:https://www.cnblogs.com/dkplus/p/8919423.html
Copyright © 2011-2022 走看看