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;

猜你喜欢

转载自www.cnblogs.com/dkplus/p/8919423.html