小编yca*_*ars的帖子

我可以在反应组件的构造函数中使用箭头函数吗?

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

1.

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

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

  doSomething() {}
}
Run Code Online (Sandbox Code Playgroud)

2.

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

    this.doSomeThing = () => {};
  }
}
Run Code Online (Sandbox Code Playgroud)

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

javascript constructor ecmascript-6 reactjs arrow-functions

17
推荐指数
1
解决办法
7077
查看次数