React:onClick 处理程序在每次渲染时都被调用? [英] React: onClick handler is getting called on every render?

查看:42
本文介绍了React:onClick 处理程序在每次渲染时都被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 React,并按照本教程创建了一个简单的您可以在 CodePen 中查看此处的井字游戏.>

我对在 Board 组件的 renderSquare 函数内返回的 Square 组件的 onClick 属性中的箭头函数是如何工作的感到困惑:onClick={() =>this.props.onClick(i)}.同样同样是游戏组件,我有 onClick={ (i) =>;this.handleClick(i)}.我以为我可以在没有箭头函数的情况下编写它(就像 onClick={this.handleClick(i)}),但这破坏了游戏.

解决方案

onClick 需要一个函数.箭头函数没有自己的this;使用封闭执行上下文的 this 值.箭头函数替代了下面的

onClick={this.handleClick.bind(this,i)}

当你像这样运行它时它不起作用

onClick={this.handleClick(i)}

因为在这种情况下,它将调用一个函数,并传递一个返回值,该值将在每次调用渲染时进行评估.因此,如果您在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆