react 受控组件和非受控组件

三世轮回 提交于 2019-11-29 11:33:51

受控组件:通过更新状态来更改数据

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

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!