我有一个组件,我想默认渲染为h2
。我希望消费者能够根据需要指定不同的元素。下面的代码会导致错误:
TS2604 - JSX element type 'ElementType' does not have any construct or call signatures
我想我明白为什么它失败了,TS 期望渲染一个 React 节点。为了清楚起见,反应is只要变量以大写字母开头(这是 JSX 的要求),就能够呈现作为字符串引用的元素。我之前已经在 vanilla JS + React 中成功完成了此操作,我只是不知道如何满足 TypeScript。
我怎样才能让 TypeScript 渲染它而不诉诸于elementType?: any
import React, {ReactNode} from 'react'
interface Props {
children: ReactNode;
elementType?: string;
}
export default function ({children, elementType: ElementType = 'h2'}: Props): JSX.Element {
return (
<ElementType>{children}</ElementType>
);
}
Use keyof JSX.IntrinsicElements
:
import * as React from 'react'
interface Props {
children: React.ReactNode;
elementType?: keyof JSX.IntrinsicElements;
}
export default function ({ children, elementType: ElementType = 'h2' }: Props): JSX.Element {
return (
<ElementType>{children}</ElementType>
);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)