【问题标题】:Passing React context through an HOC to a wrapped component通过 HOC 将 React 上下文传递给包装的组件
【发布时间】:2018-02-03 00:46:59
【问题描述】:

有没有一种方法可以通过 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 包裹。请帮忙?有什么方法可以传递不涉及将其作为道具传递的上下文??

【问题讨论】:

    标签: javascript reactjs ecmascript-6 redux higher-order-components


    【解决方案1】:

    问题:

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

    解决方案:

    WrappedComponent.contextTypes 设置在 HOC 中。

    说明:

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

    旁注:

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

    &lt;WrappedComponent {...this.props} {...newProps} {...this.context} /&gt;

    您应该在子组件中提供this.props.actions.doTheThing 之类的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-13
      • 2019-08-12
      • 2021-10-19
      • 1970-01-01
      相关资源
      最近更新 更多