【发布时间】:2017-12-24 02:01:03
【问题描述】:
我正在使用lifecycle 创建一个高阶组件。我需要访问包装的组件实例。我怎样才能得到它?
例如
export default function ajaxLoader(options) {
return lifecycle({
componentWillMount() {
// how to get *wrapped* component instance here?
// `this` refers to an instance of the lifecycle HOC, not the wrapped component
// i.e., I want the instance of `SomeComponent`
}
}) // this returns a function that accepts a component *class*
}
还有用法,如果你也想看看的话:
class SomeComponent extends React.PureComponent {
render() {
return <span/>;
}
}
const WrappedComponent = ajaxLoader({
// options
})(SomeComponent);
我认为如果我在我的 HOC 中覆盖 render() 方法并使用 ref=... 渲染已包装的组件,我可以获得对已包装组件的引用,但 recompose 特别胜出不要让我自己实现render 方法。
它支持整个组件 API,除了默认实现的 render() 方法(如果指定,将被覆盖;错误将被记录到控制台)。
【问题讨论】:
-
您无法在
lifecycle中获取包装的组件。你想用包装的组件做什么?我没有从您的使用示例中得到这个想法。 -
@wuct 示例并不是为了演示用例,只是为了演示结构。假设我想在包装的实例上调用自定义方法,我该怎么做?
-
无法访问
lifecycle中的包装组件或实例。您可能应该将这些方法提升到更高阶的组件,或者只使用普通的 React.Component。