受控组件:通过更新状态来更改数据
import React from ‘react’ class TodoList extends React.Component { state = { taskA: '', taskB: '', list: [] } render () { return ( <> <div> taskA <input type='text' name='taskA' value={this.state.taskA} onChange={this.handleChange} /><button onClick={this.handleAdd} name='taskA'>添加</button> </div> <div> taskB <input type='text' name='taskB' value={this.state.taskB} onChange={this.handleChange} /><button onClick={this.handleAdd} name='taskB'>添加</button> <div> <ul> this.state.map( (item, index) => <li key={ item + index }>{ item }<button onClick={() => this.handleDelete(index)}>X</button></li> ) </ul> </> ) } handleChange = (e) => { this.setState({ [e.target.name]: e.target.value }) } handleAdd = (e) => { let type = e.tatget.name let task = this.state[type] if (type === 'taskA') { task = `taskA: ${task}` } else if (type === 'taskB') { task = `taskB: ${task}` } this.setState({ list: [...this.state.list, task], [type]: '' }) } handleDelete = (index) => { const list = [...this.state.list] list.splice(index,1) this.setState({ list }) } } export default TodoList
非受控组件:使用ref 从dom中获取数据,需要操作dom
1 import React from 'react' 2 3 class UnControl extends React.Component { 4 task = React.createRef() 5 state = { 6 list: [] 7 } 8 render () { 9 return ( 10 <> 11 <div> 12 <input ref={this.task} /> 13 // <input ref={dom => {this.task=dom}} /> 14 <button onClick={this.handleAdd}>添加<button> 15 </div> 16 <ul> 17 this.state.list.map( (item, index) => 18 <li key={item+index}>{item}</li> 19 ) 20 </ul> 21 </> 22 ) 23 } 24 handleAdd = (e) => { 25 this.setState({ 26 list: [...this.state.list, e.target.current.value] 27 //list: [...this.state.list, e.target.value] 28 }) 29 } 30 31 } 32 33 export default UnControl