2017-02-15 63 views
2

我試圖解決作出反應的惱人bind要求如下屬性:擴展類和使用類的父類

class ExtendedComponent extends React.Component { 

    custom_functions: []; 

    constructor(props){ 
     super(props); 
     let self = this; 
     for (let i = 0; i < this.custom_functions.length; i++) { 
      let funcname = this.custom_functions[i]; 
      self[funcname] = self[funcname].bind(self); 
     } 
    } 
} 

class OrderMetricsController extends ExtendedComponent { 

    custom_functions: ['refreshTableOnDateChange', 'load', 'refreshTableOnTabChange']; 

    constructor(props){ 
     super(props); 
     ... 

這將排除需要

this.refreshTableOnDateChange = this.refreshTableOnDateChange.bind(this); 

現在,我得到TypeError: Cannot read property 'length' of undefined問題是this.custom_functions.length

+0

JavaScript沒有「屬性」。當你說「班級屬性」時,你的意思是什麼? –

+0

'custom_functions:[...];'肯定看起來像'class'裏面的語法錯誤。你使用的是什麼風格的JavaScript? – Bergi

+0

如果在ES6類語法中使用'bind'使你惱火,你是否考慮過_not_使用ES6類語法,並恢復使用'.createClass'和'createElement'等React幫助函數。 – Pineda

回答

2

custom_functions: ['refreshTableOnDateChange', 'load', 'refreshTableOnTabChange']; 

是類型的註釋,並this.custom_functions仍然是不確定的。相反,它應該是一個屬性初始化:

custom_functions = ['refreshTableOnDateChange', 'load', 'refreshTableOnTabChange']; 

或考慮其靜態性質,custom_functions可以是靜態屬性:

static custom_functions = ['refreshTableOnDateChange', 'load', 'refreshTableOnTabChange']; 

在這種情況下,它是在構造函數this.constructor.custom_functions訪問。

bind沒有什麼討厭的,這是JS的工作原理。

對於嚴格的命名規範,該方法可以自動地通過方法名遍歷,例如其名稱匹配on**Handler的那些約束:

const uniquePropNames = new Set([ 
    ...Object.getOwnPropertyNames(this), 
    ...Object.getOwnPropertyNames(this.constructor.prototype) 
]); 

for (const propName of uniquePropNames) { 
    if (typeof this[propName] === 'function' && /^on[A-Z]|.Handler$/.test(propName)) { 
    this[propName] = this[propName].bind(this); 
    } 
} 

一個好的選擇是@autobind decorator from core-decorators

+0

我很確定這應該是一個原型屬性,或者至少是'static',在每個實例中都沒有初始化? – Bergi

+0

@Bergi這是直接修復。但是,謝謝,我同意靜態屬性更適合這種情況。 – estus