美文网首页
React-todo-list 系列二

React-todo-list 系列二

作者: Mark同学 | 来源:发表于2019-12-10 11:59 被阅读0次

    状态组件 => 组件拆分

    • TodoList.js
    import React, { Component, Fragment } from 'react'
    import TodoItem from './TodoItem';
    
    class TodoList extends Component {
      constructor() {
        super()
        this.state = {
          list: [],
          inputValue: ''
        }
        this.handleInputChange = this.handleInputChange.bind(this)
        this.handleBtnClick = this.handleBtnClick.bind(this)
        this.handleDelete = this.handleDelete.bind(this)
      }
    
      handleBtnClick() {
        this.setState({
          list: [...this.state.list, this.state.inputValue],
          inputValue: ''
        })
      }
    
      handleInputChange(e) {
        this.setState({
          inputValue: e.target.value
        })
      }
    
      handleDelete(index) {
        const list = [...this.state.list]
        list.splice(index, 1)
        this.setState({
          list: list
        })
      }
    
      getTodoItems() {
        const { list } = this.state;
        return (
          list.map((item, index) => {
            return (
              <TodoItem 
                key={index} 
                index={index} 
                content={item} 
                delete={this.handleDelete}
              />
            )
          })
        )
      }
    
      render() {
        const { inputValue } = this.state;
        return (
          <Fragment>
            <div>
              <input value={inputValue} onChange={this.handleInputChange}/>
              <button onClick={this.handleBtnClick}>add</button>
            </div>
            <ul>{this.getTodoItems()}</ul>
          </Fragment>
        )
      }
    }
    
    export default TodoList
    
    • TodoItem.js
    import React from 'react';
    
    class TodoItem extends React.Component {
    
      constructor() {
        super()
        this.handleDelete = this.handleDelete.bind(this)
      }
    
      handleDelete() {
        this.props.delete(this.props.index)
      }
    
      render() {
        return (
          <li onClick={this.handleDelete}>{this.props.content}</li>
        )
      }
    }
    export default TodoItem
    

    相关文章

      网友评论

          本文标题:React-todo-list 系列二

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