2017-02-15 90 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