在React Component类中是否有更好的方法来绑定'this'?

问题描述 投票:9回答:2

我目前正在开发一个React应用,当组件类具有许多功能时,我发现必须绑定this有点麻烦。

示例

class Foo extends Component {
  constructor(props){
    super(props);
    this.function1 = this.function1.bind(this);
    this.function2 = this.function2.bind(this);
    this.function3 = this.function3.bind(this);
  }
  function1() {
    ...
  }
  function2() {
    ...
  }
  function3() {
    ...
  }
}

有没有更有效的方法?

javascript reactjs es6-class
2个回答
10
投票

您可以避免使用transform-class-properties Babel插件来绑定方法,这是ES7的一项实验功能。确保启用stage-0才能使用它。

[这允许在定义类方法时利用箭头函数,利用箭头函数的词法绑定,因此this引用函数的上下文(在本例中为类),如下所示:

class Foo extends Component {
    boundFunction = () => { /* 'this' points to Foo */ }
}

1
投票

您可以使用以下方法将其缩短一点:

this.function1 = :: this.function1

您需要https://babeljs.io/docs/plugins/transform-function-bind/

© www.soinside.com 2019 - 2024. All rights reserved.