扩展 classes 并在父 class 中使用 class 属性

Extending classes and using class attributes in parent 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

这个

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