function logProps(WrappedComponent) {
class LogProps extends React.Component {
componentDidUpdate(prevProps) {
console.log('old props:', prevProps);
console.log('new props:', this.props);
}
render() {
return <WrappedComponent {...this.props} />;
}
}
return LogProps;
}
class FancyButton extends React.Component {
focus() {
// ...
}
// ...
}
// Rather than exporting FancyButton, we export LogProps.
// It will render a FancyButton though.
export default logProps(FancyButton);
I have taken these pieces of code from the react documentation, however i am confused about what actually happens during
export default logProps(FancyButton);
My thoughts are that it probably calls the function logProps which in React is considered a higher order component which in that case it should being with capital letter to avoid ambiguity. The logProp function defines a class component LogProps, the class component LogProps renders an argument component FancyButton. The class component LogProps is then returned from the function.
import FancyButton from './FancyButton';
const ref = React.createRef();
// The FancyButton component we imported is the LogProps HOC.
// Even though the rendered output will be the same,
// Our ref will point to LogProps instead of the inner FancyButton component!
// This means we can't call e.g. ref.current.focus()
<FancyButton
label="Click Me"
handleClick={handleClick}
ref={ref}
/>;
The returnedcomponent(LogProps, FancyButton) from the function logProps is then imported and instantiated at
<FancyButton
label="Click Me"
handleClick={handleClick}
ref={ref}
/>
Is this correct?
Is this correct?
Almost.
As stated in docs, Higher Order Components :
is a function that takes a component and returns a new component.
HOC
s name don't start with capital letter. To simplify, the HOC function basically just returns a new and enhanced component. That's it.
This will also work:
// camel case
function logProps(WrappedComponent) {
// no name
return class extends React.Component {
render() {
return <WrappedComponent {...this.props} {...this.someEnhancements} />;
}
}
}
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.