How to get input text value on click in ReactJS

后端 未结 2 1719
梦谈多话
梦谈多话 2021-01-30 12:55

I am learning ReactJS and I want to understand how to get the input text values in ReactJS using simple onclick event. I have followed there tutorial and although i am able to g

相关标签:
2条回答
  • 2021-01-30 13:29

    First of all, you can't pass to alert second argument, use concatenation instead

    alert("Input is " + inputValue);
    

    Example

    However in order to get values from input better to use states like this

    var MyComponent = React.createClass({
      getInitialState: function () {
        return { input: '' };
      },
    
      handleChange: function(e) {
        this.setState({ input: e.target.value });
      },
    
      handleClick: function() {
        console.log(this.state.input);
      },
    
      render: function() {
        return (
          <div>
            <input type="text" onChange={ this.handleChange } />
            <input
              type="button"
              value="Alert the text input"
              onClick={this.handleClick}
            />
          </div>
        );
      }
    });
    
    ReactDOM.render(
      <MyComponent />,
      document.getElementById('container')
    );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <div id="container"></div>

    0 讨论(0)
  • 2021-01-30 13:38

    There are two ways to go about doing this.

    1. Create a state in the constructor that contains the text input. Attach an onChange event to the input box that updates state each time. Then onClick you could just alert the state object.

    2. handleClick: function() { alert(this.refs.myInput.value); },

    0 讨论(0)
提交回复
热议问题