好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

react获取input输入框的值的方法示例

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根据新的状态触发视图渲染,完成更新。

到此这篇关于react获取input输入框的值的方法示例的文章就介绍到这了,更多相关react获取input输入框的值内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/Shuiercc/article/details/81383679

查看更多关于react获取input输入框的值的方法示例的详细内容...

  阅读:87次