【问题标题】:Get input value on Click in React在 React 中点击获取输入值
【发布时间】:2017-04-23 12:13:19
【问题描述】:

我正在尝试获取输入 onClick(而不是 onChange)的值,但我真的很困惑。 (该函数应接受用户输入并将其乘以 5)

var Multiply = React.createClass({
  getInitialState: function(){
    return {number: '-'}

  },
  multiply: function(a){
    return (a * 5);
  },
 handleChange: function(e) {
    this.setState({ number: e.target.value });
  },
  handleClick: function(e) {

    this.multiply(this.state.number);
  },

  render: function () {
    return (
      <div>
        <p>multiply by 5!</p><br />
      <textarea onChange={this.handleChange}>
      </textarea><br/>
        <button  onClick={this.handleClick}>Submit</button>
        <p>result:</p> {this.state.result}

      </div>
    );
  }
});
ReactDOM.render(
    <Multiply/>,
    document.getElementById('root')
);

下面是代码链接: http://codepen.io/polinaz/pen/MmezZy?editors=0010

我的逻辑有什么问题?非常感谢一个很好的解释! 谢谢你

【问题讨论】:

    标签: javascript reactjs input onclick


    【解决方案1】:

    当您单击按钮时,它会将数字乘以 5,但您不会对乘以的数字(结果)执行任何操作。在你的 handleClick 函数中,你需要这样的东西:

    handleClick: function(e) {
        this.setState({result: this.multiply(this.state.number)});
    }
    

    【讨论】:

    • 感谢您的解释!直到现在我才注意到我的 this.state.result 什么也没做
    • this.state.result '什么都不做'是什么意思?
    【解决方案2】:

    我将结果添加到状态中,并将结果变量添加到乘法函数中,以便您可以将其存储在状态中。请往下看:

        var Multiply = React.createClass({
      getInitialState: function(){
       //added result to the initial state here 
        return {number: '-',
               result: 0}
    
      },
      multiply: function(a){
       //added result var here, and set the state to accept this result
        var result = a * 5;
        this.setState({result: result});
      },
     handleChange: function(e) {
    
        this.setState({ number: e.target.value });
      },
      handleClick: function(e) {
    
        this.multiply(this.state.number);
      },
    
      render: function () {
        return (
          <div>
            <p>multiply by 5!</p><br />
          <textarea onChange={this.handleChange}>
          </textarea><br/>
            <button  onClick={this.handleClick}>Submit</button>
            <p>result:</p> {this.state.result}
    
          </div>
        );
      }
    });
    ReactDOM.render(
        <Multiply/>,
        document.getElementById('root')
    );
    

    【讨论】:

    • 非常感谢!!
    • 欢迎您。请检查对您有帮助的答案左侧的复选标记。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多