react 获取input 输入框的值的多种方式

第一种方式 非受控组件获取
第二种方式 受控组件获取

非受控组件获取 ref

import React , {Component} from 'react';
export default class App extends Component{
 search(){
 const inpVal = this.input.value;
 console.log(inpVal);
 }
 
 render(){
 return(
  <div>
  <input type="text" ref={input => this.input = input} defaultValue="Hello"/>
  <button onClick={this.search.bind(this)}></button>
  </div>
 )
 }
}

使用defaultValue表示组件的默认状态,此时它只会被渲染一次,后续的渲染不起作用;input的值不随外部的改变而改变,由自己状态改变。

受控组件 this.setState({})

import React , {Component} from 'react';
export default class App extends Component{
 constructor(props){
 super(props);
 this.state = {
  inpValu:''
 }
 }
 
 handelChange(e){
 this.setState({
  inpValu:e.target.value
 })
 }
 
 render(){
 return(
  <div>
  <input type="text" onChange={this.handelChange.bind(this)} defaultValue={this.state.inpValu}/>
  </div>
 )
 }
}

input 输入框的值会随着用户输入的改变而改变,onChange通过对象e拿到改变之后的状态并更新state,setState根据新的状态触发视图渲染,完成更新。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。