反应 HOC 和访问道具

时间:2021-01-06 17:39:36

标签: javascript reactjs higher-order-functions higher-order-components

我正在尝试理解下面的 React HOC;

const withSecretToLife = (WrappedComponent) => {
  class HOC extends React.Component {
    render() {
      return (
        <WrappedComponent
          {...this.props}
          secretToLife={42}
        />
      );
    }
  }
    
  return HOC;
};

export default withSecretToLife;

下面是另一个组件;

import withSecretToLife from 'components/withSecretToLife';

const DisplayTheSecret = props => (
  <div>
    The secret to life is {props.secretToLife}.
  </div>
);

const WrappedComponent = withSecretToLife(DisplayTheSecret);

export default WrappedComponent;

特别是我试图理解

  1. 如果“DisplayTheSecret”可以访问道具“secretToLife”或 WrappedComponent ?看待这个 HOC 的正确方法是什么?
  2. “const WrappedComponent = withSecretToLife(DisplayTheSecret);”行在“const DisplayTheSecret = props => ()”行之后。这是标准模式吗?这很重要吗?
  3. 与上述问题相关,在我们拥有“props.secretToLife”之前,我们如何才能做到 声明/定义。对于 WrappedComponent 即 const WrappedComponent = withSecretToLife(DisplayTheSecret);
  4. 上述案例中实际消耗/使用的内容是 App.js,即 <WrappedComponent /> OR <DisplayTheSecret /> OR 中的任何一个都可以被消耗?

2 个答案:

答案 0 :(得分:0)

  1. 您创建了一个新组件 - WrappedComponent。它得到了道具 secretToLifeDisplayTheSecret 本身没有 secretToLife 属性。

  2. 在一般的实践中,你应该使用已经存在的变量 上面定义。所以 DisplayTheSecret 应该定义在它的上面 用法。但是,您可以随意使用它,因为变量和函数会自动提升到作用域的顶部。

  3. 您可以这样做,但可能会导致运行时出错。如果 您决定使用 DisplayTheSecret 组件而不包装它 与HOCTypescript 通过生成类型来解决这些问题 在开发过程中。

  4. WrappedComponentDisplayTheSecretHOC 组成。

答案 1 :(得分:0)

DisplayTheSecret 是一个简单的组件,它希望在其属性中找到 secretToLife

withSecretToLife 是一个接受 WrappedComponent 并返回另一个组件的函数(我们称之为 WrappingHOC

WrappingHOC 返回传递给 WrappedComponentwithSecretToLife,传递它自己的所有 props 并添加一个新的 - secretToLife

const WrappedComponent = withSecretToLife(DisplayTheSecret); - 这个也叫WrappedComponent,但它和上面的WrappedComponent(传递给函数的那个​​)不一样,它是WrappingHOCDisplayTheSecret我们称之为ResultingComponent

所以:

  1. secretToLife 是由 ResultingComponent 传递给 DisplayTheSecret

    的属性
  2. 顺序很重要,在开始使用之前声明一个函数总是一个好主意

  3. secretToLife 是一个普通的属性,你在创建组件时声明它

  4. DisplayTheSecret 未导出,因此不能在模块外使用,此外还可以不包装使用