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

React 19中ReactHTML类型已移除,求可行替代方案?

React 19中ReactHTML类型的替代方案

React 19不再对外导出ReactHTML类型,以下是几种可行的替代方案:

1. 直接使用JSX.IntrinsicElements

JSX.IntrinsicElements包含了所有HTML内置元素的类型定义,结构和原ReactHTML完全一致,可直接替换使用:

// 原写法
import type { ReactHTML } from 'react';
type MyElement = keyof ReactHTML;

// 新写法
type MyElement = keyof JSX.IntrinsicElements;

// 获取单个元素的工厂类型
type AnchorFactory = JSX.IntrinsicElements['a'];

2. 手动定义所需子集类型

如果只用到部分HTML元素,可以自行提取对应类型,避免引入不必要的全局类型:

import type { 
  DetailedHTMLFactory,
  AnchorHTMLAttributes,
  HTMLAttributes,
  HTMLAnchorElement,
  HTMLElement
} from 'react';

interface CustomReactHTML {
  a: DetailedHTMLFactory<AnchorHTMLAttributes<HTMLAnchorElement>, HTMLAnchorElement>;
  div: DetailedHTMLFactory<HTMLAttributes<HTMLElement>, HTMLElement>;
  // 根据需求添加其他元素类型
}

3. 结合ElementType与属性类型实现动态组件

如果是用于创建支持任意HTML元素的自定义组件,推荐用ElementType配合对应属性类型组合:

import type { ElementType, HTMLAttributes } from 'react';

type CustomComponentProps<T extends ElementType> = {
  as?: T;
} & HTMLAttributes<HTMLElementTagNameMap[T]>;

function CustomComponent<T extends ElementType = 'div'>({
  as: Component = 'div',
  ...props
}: CustomComponentProps<T>) {
  return <Component {...props} />;
}

内容的提问来源于stack exchange,提问作者Mir-Ismaili

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 15:54:55