【发布时间】: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 {}
}
}
【问题讨论】:
-
你使用
declare module 'react'而不是@types/react包有什么原因吗?看来您正在尝试重新发明轮子! -
没关系,您似乎正在尝试为每个组件的现有预定义属性集添加一些自定义属性。在这种情况下,您走在正确的轨道上,但在
interface DOMAttributes<T>中,通用 T 是元素,而不是道具。 -
没错,这个例子是完全错误的,但我希望它只是说明我的追求哈哈。我觉得必须有一种类型更多地充当 dom 元素的入口点,我可以挂钩并添加泛型。知道吗?
-
您希望如何传入
DynamicProps参数?我没有看到入口点在哪里
标签: reactjs typescript jsx css-in-js