react应用中,如何获取input的值

前端之家收集整理的这篇文章主要介绍了react应用中,如何获取input的值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在react应用中如何获取input的值,有如下两种方法

1、受控组件

  1. import React from 'react';
  2. import {render} from 'react-dom';
  3. import {createStore,bindActionCreators} from 'redux';
  4. import {Provider,connect} from 'react-redux';
  5.  
  6. class CustomTextInput extends React.Component{
  7. constructor(props){
  8. super(props);
  9. this.changeText = this.changeText.bind(this);
  10. this.getText = this.getText.bind(this);
  11. this.state = {
  12. intro: "",}
  13. }
  14. changeText(event){
  15. this.setState({intro: event.target.value})
  16. }
  17. getText(){
  18. alert(this.state.intro)
  19. }
  20. render(){
  21. return(
  22. <div>
  23. <input type="text" value={this.state.intro} onChange={this.changeText}/>
  24. <input type="button" value="取值1" onClick={this.getText}/>
  25. </div>
  26. )
  27. }
  28. }
  29. render(
  30. <CustomTextInput/>,document.getElementById('root')
  31. )

2、refs,非受控组件

  1. import React from 'react';
  2. import {render} from 'react-dom';
  3. import {createStore,connect} from 'react-redux';
  4.  
  5. class CustomTextInput extends React.Component{
  6. constructor(props){
  7. super(props);
  8. this.focusText = this.focusText.bind(this);
  9. }
  10. //定义一个focus方法
  11. focusText(){
  12. // this.textInput.focus();
  13. alert(this.textInput.value); //获取输入的值
  14. }
  15.  
  16. render(){
  17. return(
  18. <div>
  19. <input type="text" ref={(input) => {this.textInput = input; }}/>
  20. <input type="button" value="取值2" onClick={this.focusText}/>
  21. </div>
  22. )
  23. }
  24. }
  25. render(
  26. <CustomTextInput/>,document.getElementById('root')
  27. )

猜你在找的React相关文章