0

I write some script that will counting the number when we click the button in reactjs. This is my script:

var ComponentCounter = React.createClass({
    getInitialState: function() {
    return {count: 1};
  },
  doIncrement:function(){
    this.setState(function(prevState,currentProps){
        return {
        count:prevState.count+1
      };
    });
  },
  doDecrement:function(){
    this.setState(function(prevState,currentProps){
        return {
        count:prevState.count-1
      };
    });
  },
    render: function(){
    return(
        <div>
            <Button onClick={this.doIncrement}>+</Button>
            <h2>{this.state.count}</h2>
            <Button onClick={this.doDecrement}>-</Button>
      </div>);  
  }
});
ReactDOM.render(<ComponentCounter/>,document.getElementById('counter'));

But it doesn't work either when I clicked the button.

Can you fixed it and explain why?

Thanks :)

Barry Michael Doyle
  • 9,333
  • 30
  • 83
  • 143
cahyowhy
  • 553
  • 2
  • 9
  • 26

2 Answers2

0

You should bind context to your click handler method. Otherwise this inside the method will no longer point to component instance when the function is actually called. So you should do this:

   <Button onClick={this.doIncrement.bind(this)}>+</Button>
   <h2>{this.state.count}</h2>
   <Button onClick={this.doDecrement.bind(this)}>-</Button>
Bartek Fryzowicz
  • 6,464
  • 18
  • 27
0

If @Bartek's answer didn't fix your problem, another area to look at is your Button component... are you passing the onClick props to an actual DOM element?

var Button = createClass({
   ...
   render: function() {
     return <button onClick={this.props.onChange}>{this.props.children}</button>;
     //or
     return <button {...this.props} />;
   }
});
jpdelatorre
  • 3,573
  • 1
  • 20
  • 25