Higher-Order Components (HOCs) in React are functions that take a component and return a new component with enhanced functionality. They allow you to reuse logic across multiple components without duplicating code.
Here's a basic example of a HOC:
import React from 'react'; // A Higher-Order Component function withExtraInfo(WrappedComponent) { return function EnhancedComponent(props) { return ( <div> <p>This is extra info added by the HOC!</p> <WrappedComponent {...props} /> </div> ); }; } // A regular component function MyComponent() { return <p>This is my component!</p>; } // Wrap the component with the HOC const EnhancedMyComponent = withExtraInfo(MyComponent); function App() { return <EnhancedMyComponent />; } export default App;
While HOCs were more commonly used before the introduction of React hooks, they are still useful in many cases.
The above is the detailed content of Higher-Order Components (HOCs) in React. For more information, please follow other related articles on the PHP Chinese website!