我試圖擴展React Component,因爲我不喜歡反覆做這件事,需要this.onInputChange = this.onInputChange.bind(this);
。到目前爲止,我曾嘗試:延長「組件」;未捕獲的TypeError:超級表達式必須爲null或函數,而不是對象
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'? – Li357
不,我不是,現在我得到新的錯誤 – codyc4321
它會是什麼? – Li357