6

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

我有一个 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;

传递{...this.context}HOC 不起作用。只要被包裹的组件被 HOC 包裹,它this.context就是空的。{}请帮忙?有什么方法可以传递不涉及将其作为道具传递的上下文?

4

1 回答 1

5

问题:

如果未定义 contextTypes,则 context 将是一个空对象。

解决方案:

设置WrappedComponent.contextTypes HOC 内部。

解释:

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

边注:

因为您正在this.contextHOC 中扩展并在此处将其作为道具传递:

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

this.props.actions.doTheThing您应该在子组件中有可用的东西。

于 2017-08-25T05:14:54.430 回答