在 React 中,如何使用自己的参数调用多个函数?

In React, how to call multiple functions with their own arguments?

我想在点击时通过道具调用两个函数传递。请注意,它们都需要自己的参数。在 Stack Overflow 上搜索了一下之后,我找到了这个解决方案:

onclick={()=>{ f1(); f2() }}

所以我的实现如下:

onClick={() => {f1(arg); f2.bind(this, arg)}}

但是第二个函数永远不会被调用。谁能解释为什么这不起作用?我假设它有一些有约束力的问题?

f1 在父组件中:

f1(arg, event)
{
        event.preventDefault();
        // so on...
}

f2 也在父参数中,如下所示:

f2(arg)
{
     // do something with the argument 
}

它们正在传递给子组件

 render()
    {
            const { f2, arg, f1 } = this.props;
    
            return(
                <button onClick={() => {f2(arg); f1.call(this, arg)}}>
)
    }

试试这个方法

 onClick={(arg)=>{ this.f1(arg); this.f2(this, arg) }}

或者如下进行单独的函数调用。

onClick={(arg)=>{ this.f1(arg) }}

f1(values){
this.f2(values);
}

您可以将这两种方法都调用为

onClick={() =>{ this.f1(arg);this.f2(arg)}}

因为您没有调用第二个方法,只是使用绑定创建它。

当您使用 () => {} 和 onClik 时,上下文将由 arrow function 维护,之后您不需要绑定这两个函数。

这样写:

onClick={(e) => {
   this.f1(e, arg1, arg2, arg3);     // use f1, if function is defined outside of class
   this.f2(e, arg2)
}}

f1 (e, arg1, arg2, arg3) {
   e.preventDefault();
   console.log(arg1, arg2, arg3)
}

f2 (e, arg2) {
   e.preventDefault();
   console.log(arg2)
}

检查MDN DocThe bind() method creates a new function.


查看这些答案以获取有关绑定的更多详细信息:

Use of the JavaScript 'bind' method

第二个函数不起作用,因为您实际上并没有使用 bind 调用函数,您只是为将来的函数调用绑定作用域。如果要调用具有指定范围的函数,请使用 callapply

更多关于他们的信息:

编辑

对于你的情况,你可以像这样调用第二个函数:

onClick={(e) => {f1(e); f2.call(this, e)}}

Link 到沙箱: https://codesandbox.io/s/509o1lxjp