How to get value of textbox in React?

☆樱花仙子☆ 提交于 2019-12-03 20:40:59

问题


I just started using React.js, and I'm just not sure whether there is a special way to get the value of a textbox, returned in a component like this:

var LoginUsername = React.createClass({
  render: function () {
    return (
      <input type="text" autofocus="autofocus" onChange={this.handleChange} />
    )
  },
  handleChange: function (evt) {
    this.setState({ value: evt.target.value.substr(0, 100) });
  }
});

回答1:


As described in documentation You need to use controlled input. To make an input - controlled you need to specify two props on it

  1. onChange - function that would set component state to an input value every time input is changed
  2. value - input value from the component state (this.state.value in example)

Example:

  getInitialState: function() {
    return {value: 'Hello!'};
  },
  handleChange: function(event) {
    this.setState({value: event.target.value});
  },
  render: function() {
    return (
      <input
        type="text"
        value={this.state.value}
        onChange={this.handleChange}
      />
    );
  }

More specifically about textarea - here




回答2:


just update your input to the value

var LoginUsername = React.createClass({
  getInitialState:function(){
     return {
        textVal:''
     }
 },
  render: function () {
    return (
      <input type="text" value={this.state.textVal} autofocus="autofocus" onChange={this.handleChange} />
    )
  },
  handleChange: function (evt) {
    this.setState({ textVal: evt.target.value.substr(0, 100) });
  }
});

Your text input value is always in the state and you can get the same by this.state.textVal



来源:https://stackoverflow.com/questions/38420396/how-to-get-value-of-textbox-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!