Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

javascript - React HOC and accessing props

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

  1. If it "DisplayTheSecret" that gets access to the prop "secretToLife" Or the WrappedComponent ? What is the correct way to look at this HOC ?
  2. The line "const WrappedComponent = withSecretToLife(DisplayTheSecret);" is after the line "const DisplayTheSecret = props => ()". Is that a standard pattern and does it matter?
  3. Related to above question, how are we able to do "props.secretToLife" before we even have the declaration/definition . for the WrappedComponent i.e. const WrappedComponent = withSecretToLife(DisplayTheSecret);
  4. What is actually consumed/used in the above case say in App.js i.e <WrappedComponent /> OR <DisplayTheSecret /> OR either of them can be consumed ?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. You create a new component - WrappedComponent. It gets the prop secretToLife. DisplayTheSecret itself has no secretToLife prop.

  2. 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.

  3. 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.

  4. WrappedComponent which consists of DisplayTheSecret and HOC composition.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...