加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 07:21:05 所属栏目:百科 来源:网络整理
导读:在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

在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')
)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读