亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用箭頭函數(公共類字段)作為類方法?

如何使用箭頭函數(公共類字段)作為類方法?

智慧大石 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 關注
  • 1018 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號