代码之家  ›  专栏  ›  技术社区  ›  mikasa

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

  •  2
  • mikasa  · 技术社区  · 7 年前

    我想在单击时通过props调用两个函数pass。注意,他们都需要自己的论据。在对堆栈溢出进行了一些搜索之后,我找到了这个解决方案:

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

    因此,我的实现如下:

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

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

    F1在父组件中:

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

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

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

    他们正在被传递给子组件

     render()
        {
                const { f2, arg, f1 } = this.props;
    
                return(
                    <button onClick={() => {f2(arg); f1.call(this, arg)}}>
    )
        }
    
    4 回复  |  直到 6 年前
        1
  •  3
  •   Azamat Zorkanov    7 年前

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

    关于它们的更多信息: https://stackoverflow.com/a/15455043/5709697

    编辑

    对于您的案例,您可以这样调用第二个函数:

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

    链接到沙盒: https://codesandbox.io/s/509o1lxjp

        2
  •  1
  •   Krina Soni    7 年前

    试试这个方法

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

    或按如下方式进行单独的函数调用。

    onClick={(arg)=>{ this.f1(arg) }}
    
    f1(values){
    this.f2(values);
    }
    
        3
  •  1
  •   Mayank Shukla    7 年前

    因为您不调用第二个方法,而是使用bind创建它。

    当你使用 () => {} 使用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 Doc : The bind() method creates a new function.


    有关绑定的详细信息,请查看以下答案:

    Use of the JavaScript 'bind' method

    Why is JavaScript bind() necessary?

        4
  •  1
  •   Harikrishnan    7 年前

    两种方法都可以调用为

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