Javascript 扩展类并在父类中使用类属性
我已尝试解决React恼人的Javascript 扩展类并在父类中使用类属性,javascript,reactjs,ecmascript-6,es6-class,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++) {
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);
...
现在,我得到了TypeError:无法读取未定义的的属性'length',问题是this.custom\u functions.length
this
custom_functions: ['refreshTableOnDateChange', 'load', 'refreshTableOnTabChange'];
是类型注释,这是。自定义函数
仍然未定义。相反,它应该是一个属性初始值设定项:
custom_functions = ['refreshTableOnDateChange', 'load', 'refreshTableOnTabChange'];
或者考虑到其静态性质,自定义_函数
可以是静态属性:
static custom_functions = ['refreshTableOnDateChange', 'load', 'refreshTableOnTabChange'];
在这种情况下,它可以在构造函数中作为this.constructor.custom\u函数访问
在bind
中没有什么烦人的地方,这就是JS的工作方式
对于严格的命名约定,可以通过遍历方法名称自动绑定方法,例如名称与*
上的或*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);
}
}
一个好的选择是。JavaScript没有“属性”。当你说“类属性”是什么意思?custom_函数:[……]
当然看起来像类中的语法错误。您正在使用什么风格的javascript?如果在ES6类语法中使用bind
让您感到烦恼,您是否考虑过不使用ES6类语法并恢复使用React helper函数,如.createClass
和createElement
。?我非常确定这应该是一个原型属性,或者至少是static
,不是每个实例都初始化?@Bergi这是临时修复。但是谢谢,我同意静态属性更适合这种情况。
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);
}
}