React---高阶组件HOC

44 阅读1分钟

高阶组件

高阶组件就是一个函数,它接收一个组件作为参数,并返回一个新的组件。

const higherOrderComponent = (WrappedComponent) => {
  return class extends React.Component {
    render() {
      return <WrappedComponent {...this.props} />;
    }
  };
};

高阶组件的实现方式

高阶组件有两种主要的实现方式:属性代理(Props Proxy)和反向继承(Inheritance Inversion)

1、属性代理

属性代理是最常见的高阶组件实现方式。它通过包裹原始组件,拦截并修改传递给原始组件的属性,从而实现对组件的增强。

2、反向继承

反向继承是另一种实现高阶组件的方式。它通过创建一个子类来继承原始组件,并在子类中重写或扩展原始组件的行为。

应用场景

juejin.cn/post/751424…

权限控制

用户登录的鉴权功能

表单处理

场景:抽象表单状态管理(值收集、验证、提交)

数据获取

场景:封装数据获取的通用模式(加载/错误/数据状态)

性能优化

代码分割、懒加载

import React, { Suspense, lazy } from 'react';

// 高阶组件:实现懒加载
const withLazyLoading = (importComponent) => {
  const LazyComponent = lazy(importComponent);
  
  return (props) => (
    <Suspense fallback={<div>Loading...</div>}>
      <LazyComponent {...props} />
    </Suspense>
  );
};

// 使用高阶组件懒加载组件
const LazyHomePage = withLazyLoading(() => import('./HomePage'));
const LazyAboutPage = withLazyLoading(() => import('./AboutPage'));

// 在路由中使用懒加载组件
const AppRouter = () => {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={LazyHomePage} />
        <Route path="/about" component={LazyAboutPage} />
      </Switch>
    </Router>
  );
};