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}