How to bind onclick handlers to `this` properly on React

后端 未结 2 1566
既然无缘
既然无缘 2020-11-29 13:50

Explanation to why this is not a duplicate: My code is already working, I have included as a comment. The question is why the this context change when I include

2条回答
  •  孤独总比滥情好
    2020-11-29 14:45

    Thats because you are writing it inside a function which is not bound,

    Use

    var myFunction = function() {
        var targetNumber = Number(this.innerHTML);
        return this.inputDigit(targetNumber); 
      }.bind(this);
    

    or

    const myFunction = () => {
        var targetNumber = Number(this.innerHTML);
        return this.inputDigit(targetNumber); 
    }
    

    After this you need to bind the inputDigit function as well since it also uses setState

    //click handler function
    inputDigit = (digit) => {
      const { displayValue } = this.state;
      this.setState({
        displayValue: displayValue+String(digit)
      })
    }
    

    Since you want to use the button text as well, in that case you should use a separate variable in place of this to call the inputDigit function like

    class Calculator extends React.Component {
    
    // display of calculator initially zero
    state = {
      displayValue: '0'
    }
    
    //click handler function
    inputDigit(digit){
      const { displayValue } = this.state;
      this.setState({
        displayValue: displayValue+String(digit)
      })
    }
    
    componentDidMount(){
    
      //Get all number keys and attach click handler function
      var numberKeys = document.getElementsByClassName("number-keys");
      var that = this;
      var myFunction = function() {
        var targetNumber = Number(this.innerHTML);
        console.log(targetNumber);
        return that.inputDigit(targetNumber); // This is not working
      };
      for (var i = 0; i < numberKeys.length; i++) {
        numberKeys[i].onclick = myFunction;
      }
    
    }
    
    render() {
      const { displayValue } = this.state;
      return (
        
    {displayValue}
    {/* This will Work*/}
    ) } } ReactDOM.render(, document.getElementById('app'))
    
    
    

提交回复
热议问题