You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 17:54:01