react如何用ts写高阶组件
使用 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} />;
});
}
组合多个高阶组件
可以组合多个高阶组件来增强功能:
const EnhancedComponent = withHOC(withExtraProps(MyComponent));
注意事项
- 确保正确处理泛型以避免类型错误。
- 避免直接修改传入的组件,而是通过组合来增强功能。
- 使用
displayName提高调试体验。
以上方法可以帮助在 TypeScript 中编写类型安全的高阶组件。






