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

jed*_*mao 16 jsx typescript

任何人都知道如何正确添加/扩展自定义的HTML元素属性?

使用TypeScript文档来合并接口,我想我可以这样做:

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

<div block="foo" />; // error
Run Code Online (Sandbox Code Playgroud)

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

[ts]'HTMLProps'类型中不存在属性'block'.

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

namespace JSX {
    interface IntrinsicElements {
        div: React.HTMLProps<HTMLDivElement>
    }
}
Run Code Online (Sandbox Code Playgroud)

我试图重新宣布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
    }
}
Run Code Online (Sandbox Code Playgroud)

Edw*_*win 7

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

declare namespace React {

    interface HTMLProps<T> extends HTMLAttributes, ClassAttributes<T> {
    }
}
Run Code Online (Sandbox Code Playgroud)

但是新版本的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>
    )
};
Run Code Online (Sandbox Code Playgroud)

显然这非常繁琐,您可以将扩充代码放在另一个文件中,如typescript手册中的示例所示,并导入它:

import * as React from 'react';
import './react_augmented';
Run Code Online (Sandbox Code Playgroud)

但它仍然很脏.所以也许最好用类型定义文件的贡献者来解决这个问题.


jsc*_*chr 5

我想使用glamour的createElement替换css为每个元素添加一个道具。

为了增加公认的答案,模块增强似乎可以解决问题,但HTMLProps仅适用于非输入元素。扩展的正确接口似乎是HTMLAttributesSVGAttributes

declare module 'react' {
  interface HTMLAttributes<T> {
    css?: any
  }

  interface SVGAttributes<T> {
    css?: any
  }
}
Run Code Online (Sandbox Code Playgroud)

为了避免在每个组件中导入模块扩充,请重新导出createElement:

// createElement.ts
import { createElement } from 'glamor/react'

declare module 'react' {
  interface HTMLAttributes<T> {
    css?: any
  }

  interface SVGAttributes<T> {
    css?: any
  }
}

export default createElement
Run Code Online (Sandbox Code Playgroud)

然后告诉TS将我们createElement的JSX用于此tsconfig:

{
  "compilerOptions": {
    "jsx": "react",
    "jsxFactory": "createElement"
  }
}
Run Code Online (Sandbox Code Playgroud)

用法:

// MyComponent.tsx
import createElement from './createElement'

export default function MyComponent() {
  return <div css={{ color: 'red' }} />
}
Run Code Online (Sandbox Code Playgroud)