[英]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;
具体来说,我想了解
<WrappedComponent />
或<DisplayTheSecret />
或者它们中的任何一个都可以被消费?您创建一个新组件 - WrappedComponent
。 它得到了道具secretToLife
。 DisplayTheSecret
本身没有secretToLife
。
在一般实践中,您应该使用上面已经定义的变量。 所以 DisplayTheSecret 应该定义在它的用法之上。 但是,您可以随意使用它,因为变量和函数会自动提升到 scope 的顶部。
您可以这样做,但它可能会在运行时导致错误。 如果您决定使用DisplayTheSecret
组件而不用HOC
包装它。 Typescript
通过在开发过程中生成类型来解决这些问题。
WrappedComponent
由DisplayTheSecret
和HOC
组成。
DisplayTheSecret
是一个简单的组件,它希望在其属性中找到secretToLife
。
withSecretToLife
是一个 function 接受WrappedComponent
并返回另一个组件(我们称之为WrappingHOC
)
WrappingHOC
返回WrappedComponent
传递给withSecretToLife
,传递它自己的所有 props 并添加一个新的 - secretToLife
const WrappedComponent = withSecretToLife(DisplayTheSecret);
- 这个也叫 WrappedComponent,但和上面的WrappedComponent
(传给函数的那个)不一样,是WrappingHOC
和DisplayTheSecret
我们就叫它ResultingComponent
所以:
secretToLife
是ResultingComponent
传递给DisplayTheSecret
的属性
顺序很重要,在开始使用之前声明 function 总是一个好主意
secretToLife
是一个普通属性,你在创建组件时声明它
DisplayTheSecret
没有被导出,所以不能在模块之外使用,除了它可以不用包装就可以使用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.