为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

智慧大石 2019-06-15 10:36:32
如何使用箭头函数(公共类字段)作为类方法?我刚开始使用带有Reaction的ES6类,以前我已经将我的方法绑定到当前对象(在第一个示例中显示),但是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对象。
查看完整描述

3 回答

?
MMTTMM

TA贡献1869条经验 获得超4个赞

您的语法略有不同,只是在属性名称之后缺少了一个等号。

class SomeClass extends React.Component {
  handleInputChange = (val) => {
    console.log('selectionMade: ', val);
  }}

这是一个实验性的特征。您需要启用Babel中的实验特性来编译它。这里是一个实验启动的演示。

要在Babel中使用实验特性,您可以从这里..对于这个特定特性,您需要transform-class-properties插件:

{
  "plugins": [
    "transform-class-properties"
  ]}

您可以阅读更多关于类字段和静态属性的建议这里


查看完整回答
反对 回复 2019-06-15
?
泛舟湖上清波郎朗

TA贡献1818条经验 获得超3个赞

不,如果您想要创建绑定、特定于实例的方法,则必须在构造函数中这样做。但是,您可以为此使用箭头函数,而不是使用.bind关于原型方法:

class SomeClass extends React.Component {
  constructor() {
    super();
    this.handleInputChange = (val) => {
      console.log('selectionMade: ', val, this);
    };
    …
  }}

有一个提案,这可能允许您省略constructor()并直接将赋值放在具有相同功能的类范围内,但我不建议使用它,因为它是高度实验性的。

或者,您可以始终使用.bind,它允许您在原型上声明方法,然后将其绑定到构造函数中的实例。这种方法具有更大的灵活性,因为它允许从类的外部修改方法。

class SomeClass extends React.Component {
  constructor() {
    super();
    this.handleInputChange = this.handleInputChange.bind(this);
    …
  }
  handleInputChange(val) {
    console.log('selectionMade: ', val, this);
  }}


查看完整回答
反对 回复 2019-06-15
?
莫回无

TA贡献1865条经验 获得超7个赞

我知道这个问题已经得到了充分的回答,但我有一点贡献要做(对于那些不想使用实验功能的人来说)。由于必须在构造函数中绑定多个函数绑定并使其看起来很混乱的问题,我想出了一个实用方法,一旦绑定并调用构造函数,就会自动为您完成所有必要的方法绑定。


假设我有这个类的构造函数:


//src/components/PetEditor.jsx

import React from 'react';

class PetEditor extends React.Component {

  

   constructor(props){

        super(props);

        this.state = props.currentPet || {tags:[], photoUrls: []};

     

        this.tagInput = null;

        this.htmlNode = null;


        this.removeTag = this.removeTag.bind(this);

        this.handleChange = this.handleChange.bind(this);

        this.modifyState = this.modifyState.bind(this);

        this.handleKeyUp = this.handleKeyUp.bind(this);

        this.addTag = this.addTag.bind(this);

        this.removeTag = this.removeTag.bind(this);

        this.savePet = this.savePet.bind(this);

        this.addPhotoInput = this.addPhotoInput.bind(this);

        this.handleSelect = this.handleSelect.bind(this);

        

    }

    // ... actual method declarations omitted

}

看起来很乱,不是吗?现在我创建了这个实用程序方法


//src/utils/index.js

/**

 *  NB: to use this method, you need to bind it to the object instance calling it

 */

export function bindMethodsToSelf(objClass, otherMethodsToIgnore=[]){

    const self = this;

    Object.getOwnPropertyNames(objClass.prototype)

        .forEach(method => {

              //skip constructor, render and any overrides of lifecycle methods

              if(method.startsWith('component') 

                 || method==='constructor' 

                 || method==='render') return;

              //any other methods you don't want bound to self

              if(otherMethodsToIgnore.indexOf(method)>-1) return;

              //bind all other methods to class instance

              self[method] = self[method].bind(self);

         });

}

现在我所需要做的就是导入该实用程序,并向构造函数添加一个调用,并且不再需要绑定构造函数中的每个新方法。新构造函数现在看起来很干净,如下所示:


//src/components/PetEditor.jsx

import React from 'react';

import { bindMethodsToSelf } from '../utils';

class PetEditor extends React.Component {

    constructor(props){

        super(props);

        this.state = props.currentPet || {tags:[], photoUrls: []};

        this.tagInput = null;

        this.htmlNode = null;

        bindMethodsToSelf.bind(this)(PetEditor);

    }

    // ...

}


查看完整回答
反对 回复 2019-06-15
  • 3 回答
  • 0 关注
  • 902 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信