1

使用自定义 JSX pragma 时是否可以允许扩展 DOM 元素属性?

类似于情感和样式组件如何css在其 jsx 编译指示中使用道具和管理逻辑。我也想做同样的事情,但是可以通过泛型类型配置属性?

因此,例如:

// @jsx jsx

import { jsx } from 'my-lib';

...

<button<{ primary: boolean }> css={styles} primary={primary}>
  Hello world
</button>

我当前的类型定义如下所示:

interface CustomAttributes {
    css?: CSSProperties;
}


declare module 'react' {
    interface DOMAttributes extends CustomAttributes {}
}

declare global {
    namespace JSX {
        interface IntrinsicAttributes extends CustomAttributes {}
    }
}

我天真的解决方案看起来像这样:

interface CustomAttributes {
    css?: CSSProperties;
}


declare module 'react' {
    interface DOMAttributes<DynamicProps> extends CustomAttributes, DynamicProps {}
}

declare global {
    namespace JSX {
        interface IntrinsicAttributes<DynamicProps> extends CustomAttributes, DynamicProps {}
    }
}

相关问题: Styled components's 'css' prop with TypeScript

4

1 回答 1

0

您绝对可以添加一组固定的属性,但我不知道如何使其成为动态的。这工作得很好,并boolean为所有 JSX 元素添加了一个可选属性 'primary'。

interface CustomAttributes {
    primary?: boolean;
}

declare global {
    namespace JSX {
        interface IntrinsicAttributes extends React.Attributes, CustomAttributes {}
    }
}

当我们试图使其通用时,我们遇到了麻烦,因为原始接口不是通用的。添加泛型<T>会导致此错误:

TS2428:“IntrinsicAttributes”的所有声明必须具有相同的类型参数。

继承链中有一堆接口用于确定 props ( React.DetailedHTMLProps),因此您可以在其他可能的位置添加 props。

interface DOMAttributes<T>,interface HTMLAttributes<T>泛型的,但泛型类型T指的是元素的类型(即。button)而不是元素的泛型参数。可以为所有button元素添加某些道具。

我无法超越的砖墙是如何使button元素本身像您的示例一样通用,JSX.IntrinsicElements.button而不是通用的。我没有足够的信心说这绝对是不可能的,但我做不到。

于 2020-10-22T02:07:32.600 回答