为了账号安全,请及时绑定邮箱和手机立即绑定

用于从字符串创建 JSX 元素的正确 TypeScript 类型

用于从字符串创建 JSX 元素的正确 TypeScript 类型

RISEBY 2021-07-02 10:35:31
我有一个组件,我想默认将其呈现为h2. 如果他们愿意,我希望消费者能够指定不同的元素。下面的代码导致错误:TS2604 - JSX element type 'ElementType' does not have any construct or call signatures我想我明白为什么它会失败,TS 期望渲染一个 React 节点。为清楚起见,只要变量以大写字母开头(这是 JSX 要求),React就能够呈现作为字符串引用的元素。我之前在 vanilla JS + React 中成功做到了这一点,我只是不知道如何满足 TypeScript。我怎样才能让 TypeScript 在不诉诸于的情况下呈现这个 elementType?: anyimport React, {ReactNode} from 'react'interface Props {    children: ReactNode;    elementType?: string;}export default function ({children, elementType: ElementType = 'h2'}: Props): JSX.Element {    return (        <ElementType>{children}</ElementType>    );}
查看完整描述

3 回答

?
MYYA

TA贡献1868条经验 获得超4个赞

使用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>

  );

}


查看完整回答
反对 回复 2021-07-08
  • 3 回答
  • 0 关注
  • 513 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信