React:每次渲染都会调用 onClick 处理程序? [英] React: onClick handler is getting called on every render?
问题描述
我正在学习 React,并按照 本教程 创建了一个简单的您可以在 CodePen 中在此处查看的井字游戏.p>
我对箭头函数在 Square 组件的 onClick
属性中的工作方式感到困惑,该属性在 Board 组件的 renderSquare
函数内部返回:onClick={() =>this.props.onClick(i)}
.同样同样是我有 onClick={ (i) => 的 Game 组件.this.handleClick(i)}
.我以为我可以在没有箭头函数的情况下编写它(就像 onClick={this.handleClick(i)}
一样)但这会破坏游戏.
onClick
需要一个函数.箭头函数没有自己的this
;使用封闭执行上下文的 this
值.箭头函数是以下的替代品
onClick={this.handleClick.bind(this,i)}
当你运行它时它不起作用
onClick={this.handleClick(i)}
因为在这种情况下,它将调用一个函数,并且该函数将传递一个返回值,该返回值将在每次调用 render 时进行评估.因此,如果您在 onClick 函数中执行导致重新渲染的操作,例如 setState
,您的应用程序将陷入无限循环.因此 onClick
需要一个函数而不是一个值,所以除非你从 onClick
处理程序返回一个函数,否则你不应该直接调用它.
上面的箭头函数起到了将参数绑定到函数的作用
I am learning React, and followed this tutorial to create a simple Tic-Tac-Toe game that you can view here in CodePen.
I am confused about how the arrow function works in the onClick
property of the Square component that is being returned inside of the renderSquare
function of the Board component: onClick={() => this.props.onClick(i)}
. And also again similarly the Game component where I have onClick={ (i) => this.handleClick(i)}
. I assumed I could write it without the arrow function (just like onClick={this.handleClick(i)}
) but this breaks the game.
onClick
expects a function. An arrow function does not have its own this
; the this
value of the enclosing execution context is used.
Arrow function is a replacement for the following
onClick={this.handleClick.bind(this,i)}
It doesn't work when you run it like
onClick={this.handleClick(i)}
because in this case it will call a function and that will pass a return value that will be evaluate everytime render is called. So if you are doing somethings in the onClick function that causes a rerender for instance setState
you app will go in an endless loop. Thus onClick
needs a function and not a value so unless you are returning a function from the onClick
handler you should not directly call it.
Arrow function above performs the role of binding the parameter to the function
这篇关于React:每次渲染都会调用 onClick 处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!