如何使用箭头函数(公共类字段)作为类方法?

JavaScript

L西里

2020-03-11

我不熟悉将ES6类与React一起使用,以前我一直将我的方法绑定到当前对象(如第一个示例所示),但是ES6是否允许我使用箭头将类函数永久绑定到类实例?(在作为回调函数传递时很有用。)当我尝试使用CoffeeScript尝试使用它们时,我得到了错误:

class SomeClass extends React.Component {

  // Instead of this
  constructor(){
    this.handleInputChange = this.handleInputChange.bind(this)
  }

  // Can I somehow do this? Am i just getting the syntax wrong?
  handleInputChange (val) => {
    console.log('selectionMade: ', val);
  }

这样,如果我要传递SomeClass.handleInputChange给例如setTimeout,它将被限制为类实例,而不是window对象。

第610篇《如何使用箭头函数(公共类字段)作为类方法?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

0个回答

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android