I am trying to understand the below React HOC;
const withSecretToLife = (WrappedComponent) => {
class HOC extends React.Component {
render() {
return (
<WrappedComponent
{...this.props}
secretToLife={42}
/>
);
}
}
return HOC;
};
export default withSecretToLife;
And below is another component;
import withSecretToLife from 'components/withSecretToLife';
const DisplayTheSecret = props => (
<div>
The secret to life is {props.secretToLife}.
</div>
);
const WrappedComponent = withSecretToLife(DisplayTheSecret);
export default WrappedComponent;
Specifically I am trying to understand
<WrappedComponent />
OR <DisplayTheSecret />
OR either of them can be consumed?You create a new component - WrappedComponent
. It gets the prop secretToLife
. DisplayTheSecret
itself has no secretToLife
prop.
In general practise, you should use variables that already has been defined above. So DisplayTheSecret should be defined above its usage. However, you can use it however you want as variables and functions are automatically hoisted to the top of the scope.
You are able to do it, but it might result in error at runtime. If you decide to use DisplayTheSecret
component without wrapping it with HOC
. Typescript
solves these problems by generating typings during development.
WrappedComponent
which consists of DisplayTheSecret
and HOC
composition.
DisplayTheSecret
is a simple component and it expects to find secretToLife
among its properties.
withSecretToLife
is a function that accepts WrappedComponent
and returns another component (lets call it WrappingHOC
)
WrappingHOC
returns WrappedComponent
passed to withSecretToLife
, passes down all of its own props and adds a new one - secretToLife
const WrappedComponent = withSecretToLife(DisplayTheSecret);
- this one is also called WrappedComponent, but it's not the same as WrappedComponent
above (the one passed to the function), it is WrappingHOC
with DisplayTheSecret
let's call it ResultingComponent
So:
secretToLife
is a property passed by ResultingComponent
to DisplayTheSecret
The order does matter, it's always a good idea to declare a function before starting to use it
secretToLife
is a normal property, you declare it when you create a component
DisplayTheSecret
is not exported, so can't be consume outside of the module, apart from that it can be used without wrapping
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.