在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(
)
}
}
render(
,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(
{this.textInput = input; }}/>
)
}
}
render(
,document.getElementById('root')
)