PHP前端开发

React 中的高阶组件 (HOC)

百变鹏仔 3天前 #JavaScript
文章标签 高阶

react 中的高阶组件 (hoc) 是采用组件并返回具有增强功能的新组件的函数。它们允许您跨多个组件重用逻辑,而无需重复代码。

这是 hoc 的基本示例:

import React from 'react';// A Higher-Order Componentfunction withExtraInfo(WrappedComponent) {  return function EnhancedComponent(props) {    return (      <div>        <p>This is extra info added by the HOC!</p>        <wrappedcomponent></wrappedcomponent></div>    );  };}// A regular componentfunction MyComponent() {  return <p>This is my component!</p>;}// Wrap the component with the HOCconst EnhancedMyComponent = withExtraInfo(MyComponent);function App() {  return <enhancedmycomponent></enhancedmycomponent>;}export default App;

hoc 的要点:

虽然 hoc 在引入 react hooks 之前更常用,但它们在很多情况下仍然有用。