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

React的HTMLAttributes类型是否原生支持自定义data属性?如何免显式声明?

React自定义data属性的类型支持问题

React的HTMLAttributes<HTMLButtonElement>这类内置类型并不原生包含所有自定义data属性的类型声明,所以你直接给对象赋值data-testid这类属性时会触发类型错误。下面是两种无需显式声明每个data属性的解决方法:

方法一:精准支持所有data-*属性

通过定义一个专门匹配data-前缀属性的类型,合并到你的Props接口中,既保证类型安全,又能支持任意自定义data属性:

import { HTMLAttributes } from 'react'

// 匹配所有以data-开头的属性,值支持字符串、数字或布尔类型
type DataAttributes = {
  [key in `data-${string}`]: string | number | boolean;
};

interface FooProps extends HTMLAttributes<HTMLButtonElement>, DataAttributes {
  fooProp: string;
}

const fooObj: FooProps = {
  fooProp: 'yay',
  'data-testid': 'nay',
  'data-custom-number': 456 // 这类带数字的data属性也能正常支持
}

const Foo = () => <button {...fooObj}></button>

方法二:允许任意自定义属性(宽松模式)

如果你的场景需要支持除data属性外的其他自定义属性,可以给接口添加字符串索引签名:

import { HTMLAttributes } from 'react'

interface FooProps extends HTMLAttributes<HTMLButtonElement> {
  fooProp: string;
  // 允许任意字符串键的属性,值类型设为any(或根据需求调整)
  [key: string]: any;
}

const fooObj: FooProps = {
  fooProp: 'yay',
  'data-testid': 'nay',
  'custom-attribute': 'bar' // 非data前缀的自定义属性也能生效
}

const Foo = () => <button {...fooObj}></button>

额外说明:如果只是在JSX中直接写属性而不封装成对象,TypeScript不会报错——比如<button data-testid="nay"></button>是完全合法的,只有当你需要把属性封装成带明确类型的对象时,才需要通过上述方式扩展类型。

内容的提问来源于stack exchange,提问作者geoyws

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 12:50:09