TypeScript开发React时如何让自定义组件支持标准DOM元素props
React+TypeScript组件支持原生HTML属性的解决方案
你需要使用React内置的HTMLAttributes类型来扩展你的自定义Props,它包含了所有HTML元素通用的标准属性定义,无需你手动逐个声明className、style、id、title、lang等属性。
正确实现方式
1. 类型导入
import React, { HTMLAttributes } from 'react';
2. 扩展自定义Props
直接让你的ExampleProps继承HTMLAttributes<HTMLElement>即可:
export interface ExampleProps extends HTMLAttributes<HTMLElement> { someProp: string; anotherProp: React.ReactNode; }
3. 完整组件示例
import React, { HTMLAttributes } from 'react'; export interface ExampleProps extends HTMLAttributes<HTMLElement> { someProp: string; anotherProp: React.ReactNode; } export default function Example({ someProp, anotherProp, ...props }: ExampleProps) { return ( <div {...props}> {anotherProp} </div> ); }
完成上述修改后,你就可以正常使用期望的组件调用方式,不会再有属性不存在的报错。
补充说明
- 之前你使用的
PropsWithChildren仅会为类型增加children属性,不包含任何HTML原生属性,因此无法满足需求。 - 如果你的组件根元素是特定HTML元素(比如button、input),可以使用更精准的专属属性类型:
- 按钮:
ButtonHTMLAttributes<HTMLButtonElement> - 输入框:
InputHTMLAttributes<HTMLInputElement> - 也可以直接用
ComponentProps<'div'>这种写法获取对应标签的全量属性
- 按钮:
- 如果需要排除部分原生属性不允许用户传入,可以用
Omit工具类型,比如:extends Omit<HTMLAttributes<HTMLElement>, 'dir' | 'hidden'>
内容的提问来源于stack exchange,提问作者kaan_atakan
相关产品推荐
相关产品推荐

