**课程名称:** React16.4 快速上手
**课程章节:第2章 React实战
课程讲师: Dell
课程内容:
1、首先创建一个todolist.js组件
import React from 'react' class TodoList extends React.Component { render(){ return ( <div> todolist </div> ) } }
2、定义输入input还有渲染的ul
import React from 'react' class TodoList extends React.Component { render(){ return ( <div> <div> <input /> <button>add </button> </div> <ul> <li>学习react</li> <li>学习vue</li> </ul> </div> ) } }
3、添加state,循环渲染state
import React from 'react' class TodoList extends React.Component { constructor(props){ super(props); this.state = { list:[ 'learn react', 'learn english' ], } } handleBthClick(){ this.setState({ list:[...this.state.list,this.state.inputValue], }) } render(){ return ( <div> <div> <input /> <button onClick={this.handleBthClick.bind(this)}>add </button> </div> <ul> { · this.state.list.map((item,index) => { return <li key={index} >{item}</li> }) } </ul> </div> ) } }
4、对input添加绑定事件实现添加
import React from 'react' class TodoList extends React.Component { constructor(props){ super(props); this.state = { list:[ 'learn react', 'learn english' ], inputValue:'' } } handleBthClick(){ this.setState({ list:[...this.state.list,this.state.inputValue], inputValue:'' }) this.state.list.push('hello world') } handleInputChange(e){] this.setState({ inputValue:e.target.value }) } render(){ return ( <div> <div> <input onClick={this.handleInputChange.bind(this)} /> <button onClick={this.handleBthClick.bind(this)}>add </button> </div> <ul> { · this.state.list.map((item,index) => { return <li key={index} onClick={this.handleItemClick.bind(this)}>{item}</li> }) } </ul> </div> ) } }
5、给每一个li删除事件
import React from 'react' class TodoList extends React.Component { constructor(props){ super(props); this.state = { list:[ 'learn react', 'learn english' ], inputValue:'' } } handleBthClick(){ this.setState({ list:[...this.state.list,this.state.inputValue], inputValue:'' }) this.state.list.push('hello world') } handleInputChange(e){] this.setState({ inputValue:e.target.value }) } handleItemClick(index){ const list = [...this.state.list] list.splice(index,1) this.setState({ list:list }) } render(){ return ( <div> <div> <input onClick={this.handleInputChange.bind(this)} /> <button onClick={this.handleBthClick.bind(this)}>add </button> </div> <ul> { · this.state.list.map((item,index) => { return <li key={index} onClick={this.handleItemClick.bind(this,index)}>{item}</li> }) } </ul> </div> ) } }
课程收获:
学习到了在react中需要在最外层嵌套一个外部标签