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
相关产品推荐
相关产品推荐

