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

The*_*ice 6 javascript ecmascript-6 reactjs redux higher-order-components

有没有办法可以通过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} />
      );
    }
  }
};
Run Code Online (Sandbox Code Playgroud)

包裹组件:

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;
Run Code Online (Sandbox Code Playgroud)

通过{...this.context}HOC不起作用.只要包装的组件被HOC包裹,它this.context就是空{}的.请帮忙?有没有办法传递不涉及将其作为道具传递的上下文?

Dav*_*ins 5

问题:

如果未定义contextTypes,则上下文将是空对象.

解决方案:

设置WrappedComponent.contextTypes 在 HOC内.

说明:

在未修复的代码中,contextTypesfor SomeComponent未被设置.当SomeComponent得到由装饰@withACoolThing,所做的任何更改,以SomeComponent实际发生的事情DoACoolThing,并contextTypes为SomeComponent永远不会被设置成它最终被一个空的对象{}.

边注:

因为你this.context在HOC 中扩展并将其作为道具传递到这里:

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

你应该this.props.actions.doTheThing在子组件中有类似的东西.