gpt4 book ai didi

typescript - 如何向 TypeScript/JSX 中的现有 HTML 元素添加属性?

转载 作者:搜寻专家 更新时间:2023-10-30 20:32:13 24 4
gpt4 key购买 nike

有人知道如何使用自定义属性正确添加/扩展所有原生 HTML 元素属性吗?

the TypeScript documentation for merging interfaces ,我认为我可以这样做:

interface HTMLElement {
block?: BEM.Block;
element?: BEM.Element;
modifiers?: BEM.Modifiers;
}

<div block="foo" />; // error

但我在 vscode 1.6.1(最新)中收到以下 Intellisense 错误:

[ts] Property 'block' does not exist on type 'HTMLProps'.

HTMLProps他们指的是 React.HTMLProps<T>div元素被声明为像这样使用它:

namespace JSX {
interface IntrinsicElements {
div: React.HTMLProps<HTMLDivElement>
}
}

我尝试重新声明 div ,但无济于事。

相关:https://github.com/Microsoft/TypeScript/issues/11684

编辑:这是最终对我有用的东西:

declare module 'react' {
interface HTMLAttributes<T> extends DOMAttributes<T> {
block?: string
element?: string
modifiers?: Modifiers // <-- custom interface
}
}

最佳答案

看起来在旧版本的类型定义文件 (v0.14) 中,接口(interface)只是在全局 React 命名空间下声明,因此以前您可以使用标准的合并语法。

declare namespace React {

interface HTMLProps<T> extends HTMLAttributes, ClassAttributes<T> {
}
}

但是新版本的 d.ts 文件 (v15.0) 已经在模块中声明了所有内容。由于模块不支持合并,据我所知,目前唯一的选择似乎是 module augmentation: https://www.typescriptlang.org/docs/handbook/declaration-merging.html

我做了以下实验并且对我有用:

import * as React from 'react';

declare module 'react' {
interface HTMLProps<T> {
block?:string;
element?:string;
modifiers?:string;
}

}

export const Foo = () => {

return (
<div block="123" element="456">
</div>
)
};

显然这很乏味,您可以将增强代码放在另一个文件中,如 typescript 手册中的示例所示,然后导入它:

import * as React from 'react';
import './react_augmented';

但它仍然很脏。因此,也许最好与类型定义文件的贡献者一起解决这个问题。

关于typescript - 如何向 TypeScript/JSX 中的现有 HTML 元素添加属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40093655/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com