有没有办法在React Component类中绑定'this'?

Far*_*han 9 javascript reactjs es6-class

我正在研究一个反应应用程序,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() {
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

有没有更有效的方法来做到这一点?

小智 10

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

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

class Foo extends Component {
    boundFunction = () => { /* 'this' points to Foo */ }
}
Run Code Online (Sandbox Code Playgroud)