React 高阶组件(HOC)高级技巧

高阶组件(HOC)在 React 中是一种强大的模式,它允许你将共享逻辑抽象出来,然后封装在组件中,供其他组件重用。本文将探讨一些高级技巧,帮助你更好地利用 HOC。

1. 通用组件

创建一个通用的 HOC,它可以在多个组件中使用,减少代码冗余。

function withOptionalProp(WrappedComponent, propName, defaultProps) {
  return function EnhancedComponent(props) {
    const { [propName]: optionalProp, ...otherProps } = props;
    return <WrappedComponent {...otherProps} {...(optionalProp ? { [propName]: optionalProp } : defaultProps)} />;
  };
}

2. 钩子利用

使用 React 钩子(Hooks)与 HOC 结合,实现更灵活的组件。

import { useState, useEffect } from 'react';

function withOptionalHook(WrappedComponent, propName, defaultProps) {
  return function EnhancedComponent(props) {
    const [optionalProp, setOptionalProp] = useState(defaultProps[propName]);

    useEffect(() => {
      setOptionalProp(props[propName]);
    }, [props[propName]]);

    return <WrappedComponent {...props} {...(optionalProp ? { [propName]: optionalProp } : defaultProps)} />;
  };
}

3. 主题切换

使用 HOC 实现主题切换功能。

function withTheme(WrappedComponent) {
  return function EnhancedComponent(props) {
    const theme = { color: 'blue', background: 'lightblue' };
    return <WrappedComponent {...props} theme={theme} />;
  };
}

4. 性能优化

使用 HOC 实现组件的懒加载。

function lazyLoadComponent(WrappedComponent) {
  const LazyComponent = React.lazy(() => import(WrappedComponent));

  return function EnhancedComponent(props) {
    return <LazyComponent {...props} />;
  };
}

更多高级技巧,请访问React 高阶组件教程

React_HOC