This snippet came from a medium article. Why does the first <button onClick={this.handleClick1()}>click 1</button>
have access to the actual properties in the class?
/**
* Can you explain the differences between all those ways
* of passing function to a component?
*
* What happens when you click each of the buttons?
*/
/**
* Can you explain the differences between all those ways
* of passing function to a component?
*
* What happens when you click each of the buttons?
*/
class App extends React.Component {
constructor() {
super();
this.name = 'MyComponent';
this.handleClick2 = this.handleClick1.bind(this);
}
handleClick1() {
alert(this.name);
}
handleClick3 = () => alert(this.name);
render() {
return (
<div>
<button onClick={this.handleClick1()}>click 1</button>
<button onClick={this.handleClick1}>click 2</button>
<button onClick={this.handleClick2}>click 3</button>
<button onClick={this.handleClick3}>click 4</button>
</div>
);
}
}
Why does the first
<button onClick={this.handleClick1()}>click 1</button>
have access to the actual properties in the class?
this.handleClick1()
invokes the function right then and there, ie not when the event is triggered later. handleClick1
returns undefined
so no event handler is actually bound.
And since the function is called as object property ( xy()
), onClick1
's own this
value is set to the value before the .
(also this
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.