【发布时间】: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