【发布时间】:2021-04-12 11:46:59
【问题描述】:
我正在尝试理解下面的 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;
特别是我想了解
- 如果它是“DisplayTheSecret”,它可以访问道具“secretToLife”或 WrappedComponent?看待这个 HOC 的正确方法是什么?
- “const WrappedComponent = withSecretToLife(DisplayTheSecret);”这一行在“const DisplayTheSecret = props => ()”行之后。这是一个标准模式吗?重要吗?
- 与上述问题相关,我们如何才能在我们拥有“props.secretToLife”之前 声明/定义。对于 WrappedComponent 即 const WrappedComponent = withSecretToLife(DisplayTheSecret);
- 在上述情况下,App.js 中实际消耗/使用的内容,即
<WrappedComponent />或<DisplayTheSecret />或其中任何一个都可以使用?
【问题讨论】:
标签: javascript reactjs higher-order-functions higher-order-components