繁体   English   中英

React HOC 和访问道具

[英]React HOC and accessing props

我试图理解下面的 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 /><DisplayTheSecret />或者它们中的任何一个都可以被消费?
  1. 您创建一个新组件 - WrappedComponent 它得到了道具secretToLife DisplayTheSecret本身没有secretToLife

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

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

  4. WrappedComponentDisplayTheSecretHOC组成。

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

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

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

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

所以:

  1. secretToLifeResultingComponent传递给DisplayTheSecret的属性

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

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

  4. DisplayTheSecret没有被导出,所以不能在模块之外使用,除了它可以不用包装就可以使用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM