【发布时间】:2019-11-02 15:57:13
【问题描述】:
我有一个组件,我想默认呈现为h2。我希望消费者能够根据需要指定不同的元素。下面的代码导致错误:
TS2604 - JSX element type 'ElementType' does not have any construct or call signatures
我想我明白它为什么会失败,TS 期望渲染一个 React 节点。为清楚起见,只要变量以大写字母开头(这是 JSX 要求),React 就能够将引用的元素呈现为字符串。我之前在 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>
);
}
【问题讨论】:
标签: javascript reactjs typescript