react中的ref在input中的詳解


當我們在項目中遇見文本輸入框的時候,獲取時刻輸入框中的值

1、受控組件

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};
  }
 render() {
    return (
          <input type="text" value={this.state.value} onChange={this.handleChange} />
    );
  }
   handleChange(event) {
    this.setState({value: event.target.value});
  }
}

2、非受控組件

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};
  }
 render() {
    return (
          <input 
          type="text"
          ref={el=>this.input =el}
           placeholder="演出/藝人/場館"//輸入框中默認的value
       />
      <button
          onClick={
             this.Searchtitle.bind(this)
          }
      ></button>
    );
  }
  Searchtitle(){
    console.log(this.input.value) //實時的獲取輸入框中的值
  }
}

 


免責聲明!

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



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