An updated answer in 2019, we can choose to use bind(this) or not at present.
1) In the traditional way, we can use bind(this) in the constructor, so when we use the function as a JSX callback, the context of this is the class itself.
class App1 extends React.Component { constructor(props) { super(props);
2) If we define a function as an attribute / field of a class, we no longer need to use bind(this) .
class App2 extends React.Component { changeColor = e => { e.currentTarget.style.backgroundColor = "#00FF00"; console.log(this.props); }; render() { return ( <div> <button onClick={this.changeColor}> button 1</button> </div> ); } }
3) If we use the arrow function as a JSX callback, we also do not need to use bind(this) . And even more, we can pass parameters. It looks good, doesn't it? but its flaw is a performance issue, see ReactJS for details .
class App3 extends React.Component { changeColor(e, colorHex) { e.currentTarget.style.backgroundColor = colorHex; console.log(this.props); } render() { return ( <div> <button onClick={e => this.changeColor(e, "#ff0000")}> button 1</button> </div> ); } }
And I created Codepen to demonstrate these code snippets, hope this helps.
Eric Tan Jun 28 '19 at 0:38 2019-06-28 00:38
source share