1

I have some code as below

var React = require('react');

var Controls = React.createClass({
propTypes: {
    countdownStatus: React.PropTypes.string.isRequired,
    onStatusChange: React.PropTypes.func.isRequired
},

onStatusChange(newStatus) {
    return ()=>{
        this.props.onStatusChange(newStatus);
    }
    // this.props.onStatusChange(newStatus);
},

render() {
    var {countdownStatus} = this.props;
    var renderStartStopButton = ()=>{
        if(countdownStatus == 'started') {
            return (
                <button className="button secondary"
                    onClick={this.onStatusChange('paused')}
                >Pause</button>
            )
        } else if(countdownStatus == 'paused') {
            return (
                <button className="button primary"
                    onClick={this.onStatusChange('started')}
                >Start</button>
            )
        }
    }

    return(
        <div className="controls">
            {renderStartStopButton()}
            <button className="button alert hollow"
                onClick={this.onStatusChange('stopped')}
            >Clear</button>
        </div>
    )
}
})

module.exports = Controls;

My question is in the function of onStatusChange(newStatus), It will be wrong to use the commented statement other than return an anonymous function. But I can not get what is the difference between return a function and call the function directly.

Anyone could please help to explain the difference? thank you very much!

Richard D
  • 123
  • 3
  • 9

1 Answers1

1

You can call it directly by changing your onStatusChange(newStatus) into an arrow function also.

onStatusChange => (newStatus) {
  this.props.onStatusChange(newStatus);
}

<button className="button secondary"
   onClick={() => this.onStatusChange('paused')}
 >Pause</button>

OR by

<button className="button alert hollow"
   onClick={this.onStatusChange.bind(this,'stopped')}
 >Clear</button>

The reason is that arrow function binds the context, here it's bind this and passing whatever in the parameter list. In the second example, if you are not using arrow function you have to pass this along with the parameter(s).

Syam Pillai
  • 4,967
  • 2
  • 26
  • 42
  • Hi Syam Pillai, thanks for your reply. Your solution 2 and 3 are good to pass test. But the first solution, I found I still need to bind it onClick to get it work. For the arrow function, do you mean " onStatusChange: (newStatu)=>{ this.props.onStatusChange(newStatus)} " ? It will be error if I use onClick={this.onStatusChange('stopped')}. But it will be good to use onClick={()=>{this.onStatusChange('stopped')} – Richard D Sep 26 '17 at 12:57
  • Ohh yes, my mistake. The first one can only use with the second one since you have to pass a parameter – Syam Pillai Sep 26 '17 at 12:59
  • Looks like do not need to use arrow function for onStatusChange itself. – Richard D Sep 26 '17 at 13:08