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