gpt4 book ai didi

javascript - react : Pass `this` to onClick with multiple functions

转载 作者:行者123 更新时间:2023-11-30 11:07:24 25 4
gpt4 key购买 nike

我是 including this Stack Overflow thread因为我在这种情况下一直严重依赖它,但我不太确定如何为我的案例使用正确的语法。

在该线程中提供的多种解决方案中,这里是一个如何制作 onClick 的示例。具有多种功能:

<a href="#" onClick={(event) => { func1(); func2();}}>Test Link</a>

尝试应用 onClick 的这种情况我的代码具有多种功能,我有这个:

<span className={mobileMenuClass.join(' ')} 
onClick={(event) => {this.toggle.bind(this); this.togglePopup.bind(this)}}>
<span id="menu-rect-top"></span>
<span id="menu-rect-middle"></span>
<span id="menu-rect-bottom"></span>
</span>

这不会导致任何错误,但两个函数都不会触发。

我首先用一个函数编写了 onClick,如下所示:

onClick={this.toggle.bind(this)}

...这确实有效,但一旦我添加了第二个功能,两者都不再有效。尝试使用其他功能...

onClick={this.togglePopup.bind(this)}

...也按预期工作。

我想我可以给这个onClick单个handleClick函数,像这样:

onClick={handleClick()}

...但也不确定如何使用这两个 bind这些功能所需的 s。

最佳答案

onClick={handleClick()} 是传递处理程序的不正确方法,因为 handleClick 被立即调用并且可能返回 undefined 而不是功能。

可以安全地假设 toggletogglePopup 是未绑定(bind)的类原型(prototype)方法:

class Comp extends Component {
toggle() { ... }
togglePopup() { ... }
...
}

函数不会触发,因为它们没有被调用:

onClick={(event) => {this.toggle.bind(this); this.togglePopup.bind(this)}}

this.toggle.bind(this) 绑定(bind)一个函数并返回绑定(bind)函数。它不调用函数。仅当函数作为回调传递并且将在错误的上下文中调用时才需要绑定(bind)函数。虽然这些函数没有作为回调传递,而是使用正确的 this 上下文就地调用,因此它们不需要绑定(bind):

onClick={(event) => {this.toggle(); this.togglePopup()}}

关于javascript - react : Pass `this` to onClick with multiple functions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55092884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com