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

查看:28
本文介绍了React:当它在另一个函数内部时不能调用 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>

但是如果我设置按钮来调用我在渲染函数上方定义的函数,如下所示:

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()}

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

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() 方法创建一个新函数,该函数在调用时将其 this 关键字设置为所提供的值,并在调用新函数时在任何提供的参数之前提供给定的参数序列.文档

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. docs

此外,您将 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();
}

我编辑了答案,使其使用箭头功能.但是,我不喜欢这样做,因为它使代码有点麻烦,而是 bind 构造函数中的所有函数,就像@patrick-w-mcmahon 所做的那样.

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.

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

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