我有一个更高阶的组件。我可以从 HOC 继承 props
到我的包装组件中,但我也想继承它的方法/函数。执行此操作的最佳方法是什么。
我想使用 this.myHocFunc
,而不是 this.props.myHocFunc
。我也不想将 this.myHocFunc
映射到包装组件内的 this.props.myHocFunc
。理想情况下,所有逻辑都需要发生在 HOC 组件内部
这是我的 HOC 组件:
import React, { Component } from "React";
export var MyEnhance = ComposedComponent => class extends Component {
constructor() {
super();
}
myHocFunc(text) {
// text should be 'hello world'
console.log(text);
}
componentDidMount() {
}
render() {
return <ComposedComponent {...this.props} />;
}
};
这是我包装的组件:
import React from 'react';
import ReactDOM from 'react-dom';
import { MyEnhance } from "./enhance";
@MyEnhance
class MyComponent extends React.Component {
render() {
return <button onClick={this.myHocFunc('hello world')}</div>;
}
};
ReactDOM.render(<MyComponent />, document.getElementById('root'));
提前致谢
最佳答案
这似乎是一项继承工作,例如
class MyEnhancedComponent extends React.Component {
myHocFunc(text) {
console.log(text);
}
}
class MyComponent extends MyEnhancedComponent {
render() {
return <button onClick={() => this.myHocFunc('hello world')}</div>;
}
}
我不确定您对 MyEnhance 的其他要求是什么,但您可能使事情变得过于复杂。否则,您也可以显式添加该函数。
export var MyEnhance = ComposedComponent => class extends Component {
// ...
enhance(instance) {
instance.myHocFunc = this.myHocFunc.bind(instance);
}
render() {
return this.enhance(<ComposedComponent {...this.props} />);
}
}
最后,如果您确实无法使用“正常”继承,您可以看看 traits模式具有多重继承。我还写了一个very tiny library为此。
关于javascript - 如何从 React 中的 HOC(高阶组件)访问方法/函数而不将其作为 prop 传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44164519/