【发布时间】:2017-11-05 12:42:46
【问题描述】:
我正在尝试为我不喜欢一遍又一遍地做的事情扩展 React 组件,即this.onInputChange = this.onInputChange.bind(this); 要求。到目前为止,我已经尝试过:
MyComponent.js-
import React, { Component } from 'react';
// function bindReactMethod(this_value, method_name) {
// // Bind all of your custom methods, like:
// // this.onInputChange = this.onInputChange.bind(this);
// this_value[method_name] = this_value[method_name].bind(this_value)
// }
// https://stackoverflow.com/questions/15192722/javascript-extending-class
class MyComponent extends Component {
constructor(props) {
super(props);
this.bindReactMethods = this.bindReactMethods.bind(this)
}
bindReactMethods(this_value, method_name) {
// Bind all of your custom methods, like:
// this.onInputChange = this.onInputChange.bind(this);
this_value[method_name] = this_value[method_name].bind(this_value)
}
}
SearchBar.js-
import React from 'react';
import MyComponent from '../utils/MyComponent';
export default class SearchBar extends MyComponent {
constructor(props) {
super(props);
this.state = {term: ''};
this.bindReactMethods(['onInputChange'])
}
onInputChange(event) {
console.log(event.target.value);
this.setState({term: event.target.value})
}
失败
Uncaught TypeError: Super expression must either be null or a function, not object
和
MyComponent.js-
import React, { Component } from 'react';
function bindReactMethod(this_value, method_name) {
// Bind all of your custom methods, like:
// this.onInputChange = this.onInputChange.bind(this);
this_value[method_name] = this_value[method_name].bind(this_value)
}
// https://stackoverflow.com/questions/15192722/javascript-extending-class
class MyComponent extends Component {
constructor(props, custom_methods=[]) {
super(props);
try {
custom_methods.map((method_name) => {
bindReactMethod(this, method_name)
});
}
catch (error) { } // ignore error because that means the user didnt have custom methods to bind
}
}
SearchBar.js-
import React from 'react';
import MyComponent from '../utils/MyComponent';
export default class SearchBar extends MyComponent {
constructor(props) {
super(props, ['onInputChange']);
this.state = {term: ''};
}
onInputChange(event) {
console.log(event.target.value);
this.setState({term: event.target.value})
}
也失败了
Uncaught TypeError: Super expression must either be null or a function, not object
我想扩展 Component 并始终使用我的组件,此 bindReactMethods 回调是可选的。
【问题讨论】:
-
你是从模块中导出
MyComponent吗? -
不,我没有,现在我收到新错误
-
会是什么?
-
在我的辩护中,我声称 python 开发人员是借口
-
如果你不导出类,你应该在加载模块时得到一个异常,而不是在构造类时。然而,模块转译器可能不会考虑这一点。
标签: javascript reactjs ecmascript-6