ReactJS Tic Tac Toe - 用这个编写 OnClick 事件的不同方式
ReactJS Tic Tac Toe - Different Way to write OnClick Event with This
参考 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/)的解释,THIS将被自动绑定。我们如何手动绑定第二个代码?
我进行的下一次修改
<button className="square" onClick={alert('u clicked' + this)}>
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)
的 return 值分配给 onClick
属性。
参考 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/)的解释,THIS将被自动绑定。我们如何手动绑定第二个代码?
我进行的下一次修改
<button className="square" onClick={alert('u clicked' + this)}>
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)
的 return 值分配给 onClick
属性。