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

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

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

1、受控组件

import React from 'react';
import {render} from 'react-dom';
import {createStore,bindActionCreators} from 'redux';
import {Provider,connect} from 'react-redux';

class CustomTextInput extends React.Component{
    constructor(props){
        super(props);
        this.changeText = this.changeText.bind(this);
        this.getText = this.getText.bind(this);
        this.state = {
            intro: "",}
    }
    changeText(event){
        this.setState({intro: event.target.value})
    }
    getText(){
        alert(this.state.intro)
    }
    render(){
        return(
             <div>
                  <input type="text" value={this.state.intro} onChange={this.changeText}/>
                  <input type="button" value="取值1" onClick={this.getText}/>
             </div>
        )
    }
}
render(
    <CustomTextInput/>,document.getElementById('root')
)

2、refs,非受控组件

import React from 'react';
import {render} from 'react-dom';
import {createStore,connect} from 'react-redux';

class CustomTextInput extends React.Component{
    constructor(props){
        super(props);
        this.focusText = this.focusText.bind(this);       
    }
    //定义一个focus方法
    focusText(){
        // this.textInput.focus();
        alert(this.textInput.value); //获取输入的值
    }

    render(){
        return(
            <div>
                 <input type="text" ref={(input) => {this.textInput = input; }}/>
                 <input type="button" value="取值2" onClick={this.focusText}/>
            </div>
        )
    }
}
render(
    <CustomTextInput/>,document.getElementById('root')
)
原文链接:https://www.f2er.com/react/304041.html

猜你在找的React相关文章