通过 HOC 将 React 上下文传递给包装的组件

Passing React context through an HOC to a wrapped component

有没有一种方法可以通过 React 高阶组件将上下文传递给它包装的组件?

我有一个 HOC,它从其父级接收上下文并利用该上下文执行基本的通用操作,然后包装子组件,该子组件也需要访问相同的上下文以执行操作。示例:

HOC:

export default function withACoolThing(WrappedComponent) {
  return class DoACoolThing extends Component {
    static contextTypes = {
      actions: PropTypes.object,
    }

    @autobind
    doAThing() {
      this.context.actions.doTheThing();
    }

    render() {
      const newProps = {
        doAThing: this.doAThing,
      };

      return (
        <WrappedComponent {...this.props} {...newProps} {...this.context} />
      );
    }
  }
};

包装组件:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { autobind } from 'core-decorators';
import withACoolThing from 'lib/hocs/withACoolThing';


const propTypes = {
  doAThing: PropTypes.func,
};

const contextTypes = {
  actions: PropTypes.object,
};

@withACoolThing
export default class SomeComponent extends PureComponent {

  @autobind
  doSomethingSpecificToThisComponent(someData) {
    this.context.actions.doSomethingSpecificToThisComponent();
  }

  render() {
    const { actions } = this.context;

    return (
      <div styleName="SomeComponent">
        <SomeOtherThing onClick={() => this.doSomethingSpecificToThisComponent(someData)}>Do a Specific Thing</SomeOtherThing>
        <SomeOtherThing onClick={() => this.props.doAThing()}>Do a General Thing</SomeOtherThing>
      </div>
    );
  }
}

SomeComponent.propTypes = propTypes;
SomeComponent.contextTypes = contextTypes;

在 HOC 中传递 {...this.context} 无效。 this.context 是一个空的 {} 只要被包装的组件被 HOC 包装。请帮忙?有什么方法可以传递不涉及将其作为道具传递的上下文吗??

问题:

If contextTypes is not defined, then context will be an empty object.

解决方法:

在 HOC 中设置 WrappedComponent.contextTypes

解释:

在未修复的代码中,contextTypes for SomeComponent 没有被设置。当 SomeComponent@withACoolThing 装饰时,您对 SomeComponent 所做的任何更改实际上都发生在 DoACoolThing 上,并且 contextTypes 永远不会设置为 SomeComponent所以它最终成为一个空对象 {}.

旁注:

因为您在 HOC 中展开 this.context 并将其作为 props 传递到此处:

<WrappedComponent {...this.props} {...newProps} {...this.context} />

子组件中应该有 this.props.actions.doTheThing 之类的东西。