【问题标题】:Dynamic props for DOM elements using custom JSX pragma in Typescript在 Typescript 中使用自定义 JSX pragma 的 DOM 元素的动态道具
【发布时间】:2023-03-14 16:37:01
【问题描述】:

是否可以在使用自定义 JSX 编译指示时允许扩展 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

【问题讨论】:

  • 你使用declare module 'react'而不是@types/react包有什么原因吗?看来您正在尝试重新发明轮子!
  • 没关系,您似乎正在尝试为每个组件的现有预定义属性集添加一些自定义属性。在这种情况下,您走在正确的轨道上,但在 interface DOMAttributes&lt;T&gt; 中,通用 T 是元素,而不是道具。
  • 没错,这个例子是完全错误的,但我希望它只是说明我的追求哈哈。我觉得必须有一种类型更多地充当 dom 元素的入口点,我可以挂钩并添加泛型。知道吗?
  • 您希望如何传入DynamicProps 参数?我没有看到入口点在哪里

标签: reactjs typescript jsx css-in-js


【解决方案1】:

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

interface CustomAttributes {
    primary?: boolean;
}

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

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 2020-07-28
    • 2019-01-05
    • 2021-11-03
    • 1970-01-01
    • 2021-12-19
    • 2020-09-07
    • 2015-01-29
    • 2017-04-26
    • 2020-06-03
    相关资源
    最近更新 更多