【问题标题】:How to pass className to `h${headingLevel}` custom tag如何将 className 传递给`h${headingLevel}` 自定义标签
【发布时间】:2019-04-22 09:10:50
【问题描述】:

我正在创建一个带有动态级标题的自定义组件:

const HeadingTag = `h${headingLevel}`;
...
<HeadingTag className='heading'>
  {headingText}
</HeadingTag>

但是,我收到以下错误:

error TS2322: Type '{ children: string; className: string; }' is not assignable to type 'IntrinsicAttributes'.
  Property 'children' does not exist on type 'IntrinsicAttributes'.

如何将默认 HTML 属性传递给解析为默认 HTML 标签的自定义标签?

【问题讨论】:

    标签: reactjs typescript jsx


    【解决方案1】:

    您可以使用动态标签名称,但标签名称的类型必须是字符串文字类型或与标签名称对应的字符串文字类型的并集。

    不幸的是,打字稿无法理解h${headingLevel} 将评估为h 标记之一(如果headingLevel 是适当的数字或字符串文字类型联合,打字稿只是没有这种机制)。

    在这种情况下,最简单的解决方案是使用类型断言让 typescript 知道 HeadingTag 将是 'h1' | 'h2' | 'h3' | 'h4' | 'h5'| 'h6',因为我们比编译器拥有更多信息:

    const HeadingTag = `h${headingLevel}` as 'h1' | 'h2' | 'h3' | 'h4' | 'h5'| 'h6';
    <HeadingTag className='heading'>
        {headingText}
    </HeadingTag> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      • 2023-03-24
      • 2011-12-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-14
      • 2016-07-07
      相关资源
      最近更新 更多