功能调用方式之间的区别

发布于 2025-02-13 04:53:46 字数 227 浏览 0 评论 0原文

我注意到(至少在React中)有不同的方式调用功能。我会说:

onClick={myFunction}
onClick={myFunction()}
onClick={()=>myFunction}
onClick={()=>myFunction()} /*Not sure if I've seen this type*/

这一切都是正确的,它们之间有什么区别?

I have noticed that (at least in React) there are different ways to call a function. I'd say:

onClick={myFunction}
onClick={myFunction()}
onClick={()=>myFunction}
onClick={()=>myFunction()} /*Not sure if I've seen this type*/

Being the case all are correct, what are the difference between them?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

春夜浅 2025-02-20 04:53:46
  onclick = {myFunction}
 

分配myFunction OnClick


  onclick = {myFunction()}
 

调用myFunction立即将返回值(需要是另一个函数)分配给onclick

这通常是由于人们不了解()工作并想要上一个语法而导致的错误。


  onclick = {()=> myFunction}
 

创建一个新功能并将其分配给onClick

新功能提到myFunction,但对此无能为力。它是 noop

这总是一个错误。


  onclick = {()=> myFunction()} 
 

创建一个新功能,该功能调用myFunction,并将其分配给onclick

这通常是浪费资源。仅当myFunction会对事件对象做些onclick在调用时传递给事件处理程序的事件对象,这是有用的。

如果要将参数传递给myFunction(此示例没有),那么它将更加有用。

onClick={myFunction}

Assigns myFunction to onClick.


onClick={myFunction()}

Calls myFunction immediately and assigns the return value (which needs to be another function) to onClick.

This is often an error caused by people not understanding how () works and wanting the previous syntax.


onClick={()=>myFunction}

Creates a new function and assigns it to onClick.

The new function mentions myFunction but doesn't do anything with it. It is a noop.

It is always a mistake.


onClick={()=>myFunction()} 

Creates a new function, which calls myFunction, and assigns it to onClick.

This is usually a waste of resources. It is useful only if myFunction would do something with the event object that onClick passes to the event handler when called and you want to prevent that.

If you were to pass arguments to myFunction (which this example does not) then it would be more generally useful.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文