小编典典

我可以在react组件的构造函数中使用箭头功能吗?

reactjs

这个问题与使用React时类似。是否最好在构造函数中使用胖箭头函数或绑定函数?但是有点不同。您可以将函数绑定到this构造函数中,或者仅在构造函数中应用箭头函数。请注意,我只能在项目中使用ES6语法。

1。

class Test extends React.Component{
  constructor(props) {
    super(props);

    this.doSomeThing = this.doSomeThing.bind(this);
  }

  doSomething() {}
}

2。

class Test extends React.Component{
  constructor(props) {
    super(props);

    this.doSomeThing = () => {};
  }
}

这两种方式的优缺点是什么?谢谢。


阅读 235

收藏
2020-07-22

共1个答案

小编典典

由于某些原因,选项1通常更可取。

class Test extends React.Component{
  constructor(props) {
    super(props);

    this.doSomeThing = this.doSomeThing.bind(this);
  }

  doSomething() {}
}

原型方法更易于扩展。子类可以覆盖或扩展doSomething

doSomething() {
  super.doSomething();
  ...
}

当实例属性

this.doSomeThing = () => {};

或ES.next class字段

doSomeThing = () => {}

代替使用,调用super.doSomething()是不可能的,因为该方法未在原型上定义。覆盖它会导致在this.doSomeThing父和子构造函数中两次分配属性。

混合方法也可以使用原型方法:

class Foo extends Bar {...}
Foo.prototype.doSomething = Test.prototype.doSomething;

原型方法更具可测试性。在类实例化之前,可以对它们进行间谍,添加或模拟:

spyOn(Foo.prototype, 'doSomething').and.callThrough();

在某些情况下,这可以避免比赛条件。

2020-07-22