此摘录来自一篇中篇文章。为什么第一个<button onClick={this.handleClick1()}>click 1</button>
可以访问该类中的实际属性?
/**
* 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>
);
}
}
答案 0 :(得分:1)
为什么第一个
<button onClick={this.handleClick1()}>click 1</button>
可以访问该类中的实际属性?
this.handleClick1()
随即在此位置调用该函数,即稍后触发该事件时不。 handleClick1
返回undefined
,因此实际上没有绑定任何事件处理程序。
并且由于该函数称为对象属性(x.y()
),因此onClick1
自己的this
值设置为.
之前的值(也称为{{ 1}})。
答案 1 :(得分:0)