反应:当prop函数在另一个函数内部时,不能调用它吗? [英] React: Can't call prop function when it is inside of another function?

查看:68
本文介绍了反应:当prop函数在另一个函数内部时,不能调用它吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按照其教程中的说明来移动Auth0登录功能.如果像这样使用它,我就能使它工作:

I am trying to move over the Auth0 login function as described in their tutorial. I am able to get it work if I use it like this:

<button className="btn" onClick={this.props.route.auth.login.bind(this)}>test</button>

但是如果我设置按钮来调用一个函数,我会在render函数上方定义如下:

but if I set up the button to call a function I define above the render function like this:

  login() {
   this.props.route.auth.login.bind(this);
  }

然后将onclick更改为这样:

And change the onclick to be like this:

onClick={this.login()}

onClick={() => this.login()}

然后,身份验证登录模式将永远不会打开,并且我不会收到任何错误.我还向 login()添加了一个 console.log ,我可以在控制台中看到它,但是实际的登录模式从不打开?它在第一个示例中有效,但在其他示例中无效.

Then the auth login modal never opens and i receive no error. Also i added a console.log to login() and I can see it in the console, but the actual login modal never opens? It works in the first example, but not in the others.

之所以尝试将其移入函数是因为我想稍后将登录函数传递给子组件,但我无法这样做,并且我相信这是阻止我进行操作的根本原因

The reason I am attempting to move this into a function is because I would like to pass the login function down into a child component later, and I was unable to do so and I believe this to be the root issue thats preventing me.

推荐答案

bind 不会调用您的函数:

bind()方法创建一个新函数,该新函数在被调用时将其关键字设置为提供的值,并在调用新函数时提供给定的参数序列.文档

此外,您还将 onClick 属性的值设置为 login 的返回值.如果要传递对该函数的引用,则必须在没有()的情况下进行.

Also, you are setting the value of onClick prop to the return value of login. If you want to pass a reference to the function, you have to do it without the ().

您的代码应如下所示:

<button className="btn" onClick={() => this.login()}>test</button> <!-- You need to keep a reference to `this`, hence the binding -->

然后:

login() {
   this.props.route.auth.login();
}

我编辑了答案,以便使用箭头功能.但是,我宁愿不这样做,因为这样会使代码有点麻烦,并且像@ patrick-w-mcmahon一样,将代码 bind 构造函数中的所有功能都.

I edited the answer so that it uses an arrow function. However, I prefer not doing that, since it makes the code a bit cumbersome, and rather bind all the functions in the constructor, like @patrick-w-mcmahon did.

这篇关于反应:当prop函数在另一个函数内部时,不能调用它吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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