React read value of button clicked

前端 未结 4 2022
谎友^
谎友^ 2020-12-31 17:20

Sorry if this topic it\'s probably a copy of another one, but i don\'t understand what i\'m doing wrong with my code + i\'m really new to react. I tried several solutions bu

相关标签:
4条回答
  • 2020-12-31 17:53
    • In handleInput function you were passing the "props" but using using "this.props"
    • onClick should be there for every button
    • Should not pass the string 'value' rather do this "onClick={(e) => this.handleInput(e)}"
    • you can access with event.target.value
    0 讨论(0)
  • 2020-12-31 17:55

    You could use the event object. Something like:

        handleInput = e => {
          const buttonValue = e.target.value;
          console.log(buttonValue);
          //some logic
    }
    

    And then you could add the method on the onClick event, passing the event object as well.

       onClick = {this.handleInput}
    
    0 讨论(0)
  • 2020-12-31 17:57

    You are sending and receiving data in a wrong way. First, you need to use onClick={this.handleInput} or onClick={(e) => this.handleInput(e,'value')} instead of onClick={() => this.handleInput('value')} because you are sending 'value' string in function.

    <div className="keyboardRow roundBorder" value={"example"} onClick={e => this.handleInput(e, "value")} >
    

    And then receive in following ways:

    handleInput(e) {
        console.log(e.target.value);
    }
    

    You ca check the working demo.

    0 讨论(0)
  • 2020-12-31 18:02

    First of all, your buttons don't currently do anything when clicked, so what we're going to need to do is add an onClick to each of your buttons: <Button onClick={this.handleInput} value="clear">C</Button>.

    This will pass the event to handleInput.

    To get the value of the button clicked we can do:

    handleInput(el) {
        console.log(el.target.value);
    }
    
    0 讨论(0)
提交回复
热议问题