当前位置:首页 > React

react如何用ts写高阶组件

2026-01-25 20:52:00React

使用 TypeScript 编写 React 高阶组件(HOC)

基本高阶组件结构

高阶组件(HOC)是一个函数,接收一个组件并返回一个新的组件。以下是 TypeScript 的基本实现方式:

import React, { ComponentType } from 'react';

function withHOC<T>(WrappedComponent: ComponentType<T>) {
  return function (props: T) {
    return <WrappedComponent {...props} />;
  };
}

添加额外属性

如果需要为高阶组件添加额外属性,可以通过泛型扩展:

interface WithExtraProps {
  extraProp: string;
}

function withExtraProps<T>(WrappedComponent: ComponentType<T>) {
  return function (props: T & WithExtraProps) {
    return <WrappedComponent {...props} />;
  };
}

注入 Props

高阶组件可以通过注入新的 props 来增强组件功能:

react如何用ts写高阶组件

function withInjectedProps<T>(WrappedComponent: ComponentType<T>) {
  return function (props: Omit<T, 'injectedProp'>) {
    const injectedProps = {
      injectedProp: 'This is injected',
    };
    return <WrappedComponent {...(props as T)} {...injectedProps} />;
  };
}

处理组件名称

为了在调试工具中显示正确的组件名称,可以设置 displayName

function withDisplayName<T>(WrappedComponent: ComponentType<T>) {
  const ComponentWithDisplayName = (props: T) => {
    return <WrappedComponent {...props} />;
  };
  ComponentWithDisplayName.displayName = `WithDisplayName(${WrappedComponent.displayName || WrappedComponent.name})`;
  return ComponentWithDisplayName;
}

使用高阶组件

使用时,通过泛型指定组件 props 类型:

react如何用ts写高阶组件

interface MyComponentProps {
  name: string;
}

const MyComponent: React.FC<MyComponentProps> = ({ name }) => {
  return <div>{name}</div>;
};

const EnhancedComponent = withHOC(MyComponent);

高阶组件与 Ref

如果需要传递 ref,可以使用 forwardRef

function withRef<T, P>(WrappedComponent: ComponentType<T>) {
  return React.forwardRef<P, T>((props, ref) => {
    return <WrappedComponent {...props} ref={ref} />;
  });
}

组合多个高阶组件

可以组合多个高阶组件来增强功能:

const EnhancedComponent = withHOC(withExtraProps(MyComponent));

注意事项

  • 确保正确处理泛型以避免类型错误。
  • 避免直接修改传入的组件,而是通过组合来增强功能。
  • 使用 displayName 提高调试体验。

以上方法可以帮助在 TypeScript 中编写类型安全的高阶组件。

标签: 如何用高阶
分享给朋友:

相关文章

react如何用jq

react如何用jq

在React中使用jQuery React和jQuery可以一起使用,但需要注意两者的DOM操作方式不同。React使用虚拟DOM,而jQuery直接操作真实DOM。混合使用时需谨慎避免冲突。 安装…

react高阶函数如何写

react高阶函数如何写

高阶函数的基本概念 高阶函数(Higher-Order Function)是指接收函数作为参数或返回函数的函数。在React中,高阶函数常用于逻辑复用、组件增强或事件处理封装。 接收函数作为参数…

react如何用at.js

react如何用at.js

使用 AT.js 在 React 中实现 A/B 测试或个性化 AT.js 是 Adobe Target 提供的一个 JavaScript 库,用于在网页上实现 A/B 测试、个性化内容和体验。在 R…

react如何用第三方插件

react如何用第三方插件

使用第三方插件的基本步骤 安装所需的第三方插件,通过npm或yarn进行安装。例如,安装react-router-dom可以运行以下命令: npm install react-router-dom…

如何用命令行新建react项目

如何用命令行新建react项目

使用 create-react-app 创建项目 安装最新版本的 create-react-app 工具后,在命令行运行以下命令生成新项目: npx create-react-app my-ap…