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