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
176 views
in Technique[技术] by (71.8m points)

javascript - Usage of React HOC for Functional Components

I was referring to the below link (section : HOCs for Functional Components) https://rossbulat.medium.com/how-to-use-react-higher-order-components-c0be6821eb6c

In the example, below is the code for the HOC;

//functional HOC with useState hook
import React, { useState } from 'react';
function withCountState(Wrapped) {
   return function (props) {
      const [count, setCount] = useState(0);
  
      props['count'] = count;
      props['setCount'] = setCount;
      return <Wrapped {...props} />;
   }
}

Also, the Wrapped component code is as below;

const Wrapped = (props) =>  {
   const {count, setCount} = props;
   return(
     <div>
        <h1>Counter Functional Component</h1>
        <p>You clicked {count} times</p>
        <button onClick={() => setCount(count + 1)}>
           Increment count
        </button>
     </div>);
};

For applying HOC to , we use

const EnhancedWrapped = withCountState(Wrapped);

Now I have 2 questions;

  1. For consuming this component, do we just say <EnhancedWrapped> may be in our App.js or do we need anything else?
  2. What benefit do we really get out of creating this HOC?

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

1 Answer

0 votes
by (71.8m points)
  1. For consuming this component, do we just say may be in our App.js or do we need anything else? Yes, just use HOC like any other JSX component.

  2. What benefit do we really get out of creating this HOC? You can make it reusable. Let's say you want another component with different content inside, like , you could just create a new component by const AnotherEnhancedWrapped = withCountState(AnotherWrapped);


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

...