当前位置:首页 > 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 来增强组件功能:

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 类型:

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} />;
  });
}

组合多个高阶组件

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

react如何用ts写高阶组件

const EnhancedComponent = withHOC(withExtraProps(MyComponent));

注意事项

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

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

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

相关文章

如何用java

如何用java

用Java实现基础功能 Java是一种广泛使用的编程语言,适用于开发各种应用程序。以下是几个常见功能的实现方法。 打印"Hello, World!" public class HelloWorld…

如何用react做分页

如何用react做分页

使用 React 实现分页功能 分页是 Web 开发中常见的需求,React 可以通过状态管理和组件化轻松实现分页功能。以下是实现分页的几种方法。 基础分页实现 定义状态 使用 useState…

如何用react做增删

如何用react做增删

使用React实现增删功能 在React中实现增删功能通常涉及状态管理和列表渲染。以下是一个完整的实现方案: 初始化状态 需要定义一个状态来存储列表数据,可以使用useState钩子: const…

如何用react构建用户界面

如何用react构建用户界面

安装 React 环境 使用 Create React App 快速搭建项目环境,运行以下命令: npx create-react-app my-app cd my-app npm start…

如何用react写页面跳转

如何用react写页面跳转

使用React Router进行页面跳转 React Router是React生态中最常用的路由管理库,适用于单页面应用(SPA)的导航和页面跳转。以下是具体实现方法: 安装React Router…

如何用ts重构react项目

如何用ts重构react项目

使用 TypeScript 重构 React 项目的步骤 安装 TypeScript 及相关依赖 在项目中安装 TypeScript 和 React 的类型定义文件: npm install -…