【问题标题】:How to get wrapped component instance with recompose?如何使用 recompose 获取包装的组件实例?
【发布时间】: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。

标签: reactjs recompose


【解决方案1】:

如果您必须有权访问实例方法,您可以执行以下操作:

class ParentComponent extends Component {
  constructor(props) {
    super(props);
    this.childController = null;
  }

  // access child method via this.childController.instanceMethod

  render() {
    return <DecoratedChildComponent provideController={controller => this.childController = controller} />
  }
}

class ChildComponent extends Component {
  componentDidMount() {
    this.props.provideController({
      instanceMethod: this.instanceMethod,
    })
  }

  componentWillUnmount() {
    this.props.provideController(null);
  }

  instanceMethod = () => {
    console.log("I'm the instance method");
  }
}

这有点复杂,在大多数情况下是可以避免的,但是你确实需要访问一个实例方法,这样就可以了

【讨论】:

  • 这项工作。经过这么长时间寻找这是最好的解决方案谢谢你的朋友
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-23
  • 2018-09-07
  • 2014-02-22
  • 2022-08-20
相关资源
最近更新 更多