这个问题在这里已有答案:
参考ReactJS教程。 https://reactjs.org/tutorial/tutorial.html#setup-option-2-local-development-environment
<button className="square" onClick={()=>alert('u clicked' + this)}>
上面的代码工作正常。但是,当我做出改变时。
button className="square" onClick={function() {alert('u clicked: ' + this)}}>
上面的代码不起作用。
根据(https://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/)的解释,这将是自动绑定。我们如何手动绑定第二个代码?
我做了下一次修改
<button className="square" onClick={alert('u clicked' + this)}>
这是显示的,但是在加载期间它被称为。为什么?
提前致谢。
在第一个例子中,<button className="square" onClick={()=>alert('u clicked' + this)}>
,onClick
prop被赋予箭头函数,其中this
指的是创建按钮的上下文。
要以与第二个示例相同的方式绑定this
,请使用.bind(this)
跟随函数定义:
<button className="square" onClick={function() {alert('u clicked: ' + this)}.bind(this)}>
您的上一次修改会将alert('u clicked' + this)
的返回值分配给onClick
属性。