如何在自定义JSX元素上声明属性?React与Web Components适配问题
React与Web Components结合时自定义元素属性的正确声明方式
你当前的错误在于把columns属性声明在了全局的IntrinsicAttributes接口中,这不仅会让所有JSX元素都继承这个属性(不符合预期),还没有正确关联到<layout>自定义元素的类型定义上,导致ESLint无法识别该属性属于<layout>元素。
修正后的类型声明方案
你需要将columns属性直接关联到<layout>元素的类型定义中,有两种常用方式:
方式1:直接在IntrinsicElements的layout条目里添加属性
import { DOMAttributes } from "react"; type CustomElement<T> = Partial<T & DOMAttributes<T> & { children: any }>; declare global { namespace JSX { interface IntrinsicElements { ['layout']: CustomElement<HTMLDivElement> & { columns?: boolean; // 将columns属性限定为layout元素专属 }; } } }
方式2:扩展CustomElement泛型支持额外属性
如果后续还有其他自定义元素需要添加专属属性,可以用这种更灵活的方式:
import { DOMAttributes } from "react"; // 新增泛型参数接收元素专属属性 type CustomElement<T, ExtraProps = {}> = Partial<T & DOMAttributes<T> & { children: any } & ExtraProps>; declare global { namespace JSX { interface IntrinsicElements { // 传入layout独有的属性定义 ['layout']: CustomElement<HTMLDivElement, { columns?: boolean }>; } } }
说明
修改后,TypeScript和ESLint就能正确识别columns是<layout>自定义元素的专属属性,不会再报错。另外,你在JSX中写的<layout columns>等价于<layout columns={true}>,这和原生Web Components的布尔属性行为一致,是正确的写法。
内容的提问来源于stack exchange,提问作者Adrian Rosca
相关产品推荐
相关产品推荐

