第3.4章:TodoList案例优化

2019-05-13  本文已影响0人  赵羽珩

TodoList 页面

import React, { Component, Fragment } from 'react'
import './style.css'
import TodoItem from './TodoItem'

export class TodoList extends Component {
    constructor(props) {
        super(props)
        
        this.state = {
            inputValue: '',
            list: ['a','b','c','d'],
        }
        // this,指向
        this._onChangeInput = this._onChangeInput.bind(this);
        this._onClickButton = this._onClickButton.bind(this);
        this._onClickLiItem = this._onClickLiItem.bind(this);
    }
    
render() {
    return (
        <Fragment>
            <div>
                
                <input 
                    className='input'
                    value={this.state.inputValue}
                    onChange={this._onChangeInput}/>
                <button onClick={this._onClickButton}>提交</button>
            </div>
            <ul>
                {
                    this.state.list.map((item, index) => {
                        return(
                            <TodoItem 
                                key={index}
                                content={item} 
                                index={index}
                                LiItemDelete={this._onClickLiItem}
                            />
                        )
                    })
                }
            </ul>
        </Fragment>
    )
    }
    _onChangeInput(e) {
        this.setState({
            inputValue: e.target.value,
        })
    } 
    _onClickButton() {
        this.setState({
            list: [...this.state.list, this.state.inputValue],
            inputValue: '',
        })
    }
    _onClickLiItem(index) {
        const delList = [...this.state.list];
        delList.splice(index, 1)
        this.setState({
            list: delList,
        }) 
    }
}

export default TodoList

TodoItem 组件页面

import React, { Component } from 'react'

export class TodoItem extends Component {
    constructor(props) {
    super(props)
    
    this.state = {
        
    }
    this._onClickLi = this._onClickLi.bind(this);
    }
    
render() {
    return (
    <li onClick={this._onClickLi}>{this.props.content}</li>
    )
}
_onClickLi() {
    this.props.LiItemDelete(this.props.index)
}
}

export default TodoItem
上一篇下一篇

猜你喜欢

热点阅读