【问题标题】:Extending classes and using class attributes in parent class在父类中扩展类和使用类属性
【发布时间】:2017-02-15 22:56:15
【问题描述】:

我尝试解决 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

【问题讨论】:

  • JavaScript 没有“属性”。你说的“类属性”是什么意思?
  • custom_functions: […]; 肯定看起来像 class 中的语法错误。你用的是什么风格的 javascript?
  • 如果在 ES6 类语法中使用 bind 让您感到厌烦,您是否考虑过 使用 ES6 类语法并恢复使用像 .createClass 和 @ 这样的 React 辅助函数987654330@..?

标签: javascript reactjs ecmascript-6 es6-class


【解决方案1】:

这个

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

【讨论】:

  • 我很确定这应该是一个原型属性或至少static,而不是在每个实例中都初始化?
  • @Bergi 这是临时修复。但是谢谢,我同意静态属性更适合这种情况。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多