[英]React Dynamic Tag Name Using TypeScript Generics
我有一个简单的多态 React 组件,它应该只呈现标签名称(例如span
)但不呈现自定义 React 组件(例如MyComponent
)。 看起来这可以使用JSX.IntrinsicElements
来实现。 我有以下代码:
import React from "react";
type PolymorphicComponentProps<T extends keyof JSX.IntrinsicElements> = {
as?: T;
} & JSX.IntrinsicElements[T];
const PolymorphicComponent = <T extends keyof JSX.IntrinsicElements = "div">({
as: Component = "div" as T,
...rest
}: PolymorphicComponentProps<T>) => {
return <Component {...rest} />; // TS error: JSX element type 'Component' does not have any construct or call signatures.
};
通用类型T
将确定可用的 HTML 属性。 例如,如果我要将PolymorphicComponent
呈现a
标签...
<PolymorphicComponent as="a" />
...然后我会自动完成href
属性/道具。 再举一个例子,如果我要将PolymorphicComponent
呈现为img
标签......
<PolymorphicComponent as="img" />
...然后我会自动完成src
属性/道具。 这似乎按预期工作,但我仍在处理PolymorphicComponent
组件 function 定义中注释的 TypeScript 错误: JSX element type 'Component' does not have any construct or call signatures
。
我想不通的是: Component
变量( as
prop 的别名)的类型为T | (T & string)
T | (T & string)
。 我希望Component
的类型只是T
。
如果我创建这个始终呈现div
的非常简单的组件,则不会出现 TypeScript 错误:
const DivComponent = () => {
const Div: keyof JSX.IntrinsicElements = "div";
return <Div />;
};
问题:为了摆脱 TypeScript 错误,我需要进行哪些更改? 根据我的阅读,我不需要用React.createElement
替换 JSX,所以我希望尽可能保留这个组件的 JSX 版本。
我非常想知道是否有更好的方法,但这就是我想出的; 长话短说,如果您将Component
转换为React.ElementType
,那么 TS 很高兴:
type IntrinsicElement = keyof JSX.IntrinsicElements;
type PolymorphicComponentProps<T extends IntrinsicElement> = {
as?: T;
} & JSX.IntrinsicElements[T];
const PolymorphicComponent = <T extends IntrinsicElement = 'div'>({
as: elementType = 'div' as T,
...rest
}: PolymorphicComponentProps<T>) => {
const Component = elementType as ElementType;
return <Component {...rest} />;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.