Todolist.js
import React, { Component,Fragment } from 'react'; import TodoItem from './TodoItem'; import './style.css'; class Todolist extends Component { constructor(props) { //最优先执行的函数 super(props); this.state={ inputValue:'', list:[] } this.handleinputChange=this.handleinputChange.bind(this); this.handlebuttonClick=this.handlebuttonClick.bind(this); this.handleItemdelt=this.handleItemdelt.bind(this); } render() { return ( <Fragment> <div> {/*这是一个todolist*/} <label htmlFor='insertArea'>输入内容</label> <input id="insertArea" className='input' value={this.state.inputValue} onChange={this.handleinputChange} /> <button onClick={this.handlebuttonClick}> 提交 </button> </div> <ul> {this.getTodoItem()} </ul> </Fragment> ); } getTodoItem(){ return this.state.list.map((item,index)=>{ return( <TodoItem key={index} index={ index } item={ item } deleteItem={this.handleItemdelt} /> ) }) } handleinputChange(e){ const value=e.target.value; this.setState(()=>({ inputValue:value })); // this.setState({ // inputValue:e.target.value // }) } handlebuttonClick(e){ this.setState((prevState)=>{ return{ list:[...prevState.list,prevState.inputValue], inputValue:'' } }); // this.setState({ // list:[...this.state.list,this.state.inputValue], // inputValue:'' // }) } handleItemdelt(index){ // immutable // state 不允许我们坐任何的改变 this.setState((prevState)=>{ const list=[...prevState.list]; list.splice(index,1); return{list} }) // const list=[...this.state.list]; // list的一个副本 // list.splice(index,1); // this.setState({ // list:list // }) } } export default Todolist;
TodoItem.js
import React ,{ Component } from 'react'; class TodoItem extends Component{ constructor(props){ super(props); this.handleclick=this.handleclick.bind(this); } render(){ const { item }=this.props; return (<li onClick={this.handleclick} dangerouslySetInnerHTML={{__html:item}} ></li> ) } handleclick(){ const {deleteItem,index}=this.props; deleteItem(index); } } export default TodoItem;