Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何将className传递给`h${headingLevel}`自定义标记_Reactjs_Typescript_Jsx - Fatal编程技术网

Reactjs 如何将className传递给`h${headingLevel}`自定义标记

Reactjs 如何将className传递给`h${headingLevel}`自定义标记,reactjs,typescript,jsx,Reactjs,Typescript,Jsx,我正在创建具有动态级别标题的自定义组件: const HeadingTag=`h${headingLevel}`; ... {headingText} 但是,我得到以下错误: error TS2322: Type '{ children: string; className: string; }' is not assignable to type 'IntrinsicAttributes'. Property 'children' does not exist on type 'Intr

我正在创建具有动态级别标题的自定义组件:

const HeadingTag=`h${headingLevel}`;
...
{headingText}
但是,我得到以下错误:

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

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

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

不幸的是,typescript无法理解
h${headingLevel}
将计算为
h
标记之一(如果
headingLevel
是一个适当的数字或字符串文字类型联合,那么typescript就没有相应的机制)

在这种情况下,最简单的解决方案是使用类型断言让typescript知道
HeadingTag
将是
'h1''h2''h3''h4''h5''h6'

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