何时调用函数vs function()in on on? [英] When to call function vs function() in react onClick?

查看:95
本文介绍了何时调用函数vs function()in on on?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对何时调用react组件中的函数有疑问。有时我的代码会在我没有将括号添加到函数调用时中断,但并非总是如此。我在这里缺少某种规则吗?

I'm having questions about when to call a function inside a react component. Sometimes my code breaks when I don't add the brackets to a function call, but not always. Is there some sort of rule i'm missing here?

不起作用

// Callback of parent component
<Link onClick={this.props.OnNavigate}>
    A link
</Link>

工作

// Callback of parent component
<Link onClick={this.props.OnNavigate()}>
    A link
</Link>

// Callback for function of component
<li onClick={this.toggleDepartments}>other example</li>


推荐答案

foo()正在调用 foo 引用的函数。 foo 本身只是对函数的引用,它不会调用函数。

foo() is calling the function referenced by foo. foo itself is just a reference to a function, it doesn't call the function.

所以,你需要如果你想在这里和现在调用函数,请使用括号。

如果你想传递函数,你必须省略括号其他代码,所以它可以调用该函数。事件处理程序就是这种情况。 this.props.OnNavigation 应该在click事件发生时调用(这是将来的某个时间),而不是在渲染组件时调用。

So, you need to use parenthesis if you want to call the function right here and now.
You have to omit the parentheses if you want to pass the function to other code so it can call the function. That would be the case with event handlers. this.props.OnNavigation should be called when the click event happens (which is some time in the future), not when the component is rendered.

这篇关于何时调用函数vs function()in on on?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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