[英]Bind vs Arrow Function when passing onChange props (React)
When we pass an arrow function to an event handler ie onClick={() => myFunction()}
, we are causing un-necessary re-renders since this is a function definition.当我们将箭头 function 传递给事件处理程序(即onClick={() => myFunction()}
时,我们会导致不必要的重新渲染,因为这是一个 function 定义。
Instead, should onClick={myFunction.bind(this)}
be used instead of the arrow function whenever we call a function on an event handler and want access to this
?相反,每当我们在事件处理程序上调用 function 并想要访问this
时,是否应该使用onClick={myFunction.bind(this)}
而不是箭头 function ? Since it is only using a reference to the function, we are not causing a re-render each time.由于它仅使用对 function 的引用,因此我们不会每次都重新渲染。
Is the above understanding correct?上述理解正确吗? If so, why would we ever use an arrow function as an event handler prop?如果是这样,我们为什么要使用箭头 function 作为事件处理程序道具? It seems that ever since the introduction of ES6, using.bind like we do here is not usually recommended, but since it would not cause unnecessary re-renders shouldn't this be the best practice?似乎自从引入 ES6 以来,通常不建议像我们在这里使用.bind,但是由于它不会导致不必要的重新渲染,这不应该是最佳实践吗?
Since it is only using a reference to the function, we are not causing a re-render each time由于它仅使用对 function 的引用,因此我们不会每次都重新渲染
You're wrong.你错了。
The bind
method returns a new function (so will trigger a re-render). bind
方法返回一个新的 function(因此会触发重新渲染)。
To avoid re-renders, make use of the useCallback
hook.为避免重新渲染,请使用useCallback
挂钩。
Or, since you don't appear to be making use of this
inside myFunction
(otherwise () => myFunction()
would break it), just pass myFunction
itself without creating a new function.或者,由于您似乎没有在myFunction
中使用this
(否则() => myFunction()
会破坏它),只需传递myFunction
本身而不创建新的 function。
onClick={myFunction}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.