react中獲取輸入框中值的兩種方式——受控組件和非受控組件


import React, {Component} from 'react'; class Home extends Component { constructor(props) { super(props) this.state = { value: '' } this.input = React.createRef() // 需要在構造器中調用后才可以獲取到該節點的值(非受控組件) this.lookInput = this.lookInput.bind(this) }  changeValue = (event)=>{ console.log(event.target.value) this.setState({ value: event.target.value // 想雙向綁定,改變輸入框中的值時必須使用this.setState的方式 }) } geiInput() { return <input type="text" value={this.state.value} onChange={this.changeValue} /> // 通過綁定this.state中的值來獲取,受控組件
 } lookInput() { console.log(this.input)
    
 console.log(this.refs.username.value) // 直接取相關節點的值
  }
 render() { return ( <div>
                <h3>受控組件</h3>
                {this.geiInput()} <br/>
                <h3>非受控組件</h3>
                <input type="text" ref={this.input}/> // 通過ref的方式來獲取,即獲取該節點(非受控組件)
                <button onClick={this.lookInput}>提交查看輸入框的值</button>
              <input type="text" ref="username" /> // 非受控組件取值的第二種方式
         <input type="text" defaultValue="" /> // 不需雙向綁定時
 
</div>  ) } } export default Home 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM