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