Reactjs 在箭头函数中调用箭头函数

Reactjs call arrow function in an arrow function

我的 React 项目中的箭头函数有问题。

class 看起来像这样:

f1() { 
// sth...
}

f2 = (a) => () => { /* sth */ }
f3 = (b) => () => {
   this.f1();
   this.f2();
}

为什么函数f2没有被调用? F1 没问题,但 f2 似乎上下文有问题?如何解决?我需要在它工作的另一个地方调用相同的函数(f2)(onClick 事件)。我猜 'this' 有一个自动绑定的问题,但我不知道如何解决它。请帮忙。

函数 f3 是 returns 另一个函数的函数,为了调用它,您需要这样写

f3 = (b) => () => {
   this.f1();
   this.f2();
}

this.f3()()

正如@Jonas W. 和@Seblor 所建议的,您正在创建返回函数的函数。而是使用以下语法:

f1() { 
// sth...
}

f2 = (a) => { /* sth */ }
f3 = (b) => {
   this.f1();
   this.f2();
}

您的函数 f2 确实被调用了,但是 returns 另一个函数。

f2 = (a) => () => { /* sth */ }

这相当于:

f2 = (a) => {
    return () => { /* sth */ }
}

所以要调用 /* sth */,你必须使用这个:

f2()()

因为f2() returns 你的第二个函数(内部函数)。

像这样尝试。

  componentWillMount() {
    this.f3(1);
  }

  f1() { 
    console.log('calling f1');
  }

  f2 = (a) => { 
    console.log('calling f2 ' + a);
  }

  f3 = (b) => {
   this.f1();
   this.f2('text');
  }