扩展类并在父类中使用类属性

时间:2017-02-15 22:56:15

标签: javascript reactjs ecmascript-6 es6-class

我试图按如下方式解决React恼人的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

1 个答案:

答案 0 :(得分: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