我试图为HTML标题标签(h1, h2, h3等)编写一个React组件,其中标题级别是通过道具指定的。

我试着这样做:

<h{this.props.level}>Hello</h{this.props.level}>

我期望的输出是这样的:

<h1>Hello</h1>

但这行不通。

有什么办法可以做到吗?


当前回答

没有办法做到这一点,只是把它放在一个变量(第一个字母大写):

const CustomTag = `h${this.props.level}`;

<CustomTag>Hello</CustomTag>

其他回答

这就是我如何为我的项目设置它。

TypographyType.ts

import { HTMLAttributes } from 'react';

export type TagType = 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'p' | 'span';

export type HeadingType = HTMLAttributes<HTMLHeadingElement>;
export type ParagraphType = HTMLAttributes<HTMLParagraphElement>;
export type SpanType = HTMLAttributes<HTMLSpanElement>;

export type TypographyProps = (HeadingType | ParagraphType | SpanType) & {
  variant?:
    | 'h1'
    | 'h2'
    | 'h3'
    | 'h4'
    | 'h5'
    | 'h6'
    | 'body1'
    | 'body2'
    | 'subtitle1'
    | 'subtitle2'
    | 'caption'
    | 'overline'
    | 'button';
};

Typography.tsx

    import { FC } from 'react';
    import cn from 'classnames';
    import { typography } from '@/theme';
    
    import { TagType, TypographyProps } from './TypographyType';
    
    const headings = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
    const paragraphs = ['body1', 'body2', 'subtitle1', 'subtitle2'];
    const spans = ['button', 'caption', 'overline'];
    
    const Typography: FC<TypographyProps> = ({
      children,
      variant = 'body1',
      className,
      ...props
    }) => {
      const { variants } = typography;
    
      const Tag = cn({
        [`${variant}`]: headings.includes(variant),
        [`p`]: paragraphs.includes(variant),
        [`span`]: spans.includes(variant)
      }) as TagType;
    
      return (
        <Tag
          {...props}
          className={cn(
            {
              [`${variants[variant]}`]: variant,
            },
            className
          )}
        >
          {children}
        </Tag>
      );
    };
    
    export default Typography;

没有办法做到这一点,只是把它放在一个变量(第一个字母大写):

const CustomTag = `h${this.props.level}`;

<CustomTag>Hello</CustomTag>

为了完整起见,如果你想使用动态名称,你也可以直接调用React。createElement而不是使用JSX:

React.createElement(`h${this.props.level}`, null, 'Hello')

这避免了必须创建一个新的变量或组件。

道具:

React.createElement(
  `h${this.props.level}`,
  {
    foo: 'bar',
  },
  'Hello'
)

从文档中可以看出:

创建并返回一个给定类型的新React元素。类型参数可以是标签名字符串(如'div'或'span'),也可以是React组件类型(类或函数)。 用JSX编写的代码将被转换为使用React.createElement()。如果使用JSX,通常不会直接调用React.createElement()。参见React Without JSX了解更多信息。

概括robstarbuck的答案,你可以创建一个完全动态的标签组件,像这样:

const Tag = ({ tagName, children, ...props }) => (
  React.createElement(tagName, props , children)
)

你可以这样用:

const App = ({ myTagName = 'h1' }) => {
  return (
    <Tag tagName={myTagName} className="foo">
     Hello Tag!
    </Tag>
  )
}

如果你使用的是TypeScript,你会看到这样的错误:

类型'{children:字符串;}'与'IntrinsicAttributes'类型没有共同的属性。ts(2559)

TypeScript不知道CustomTag是一个有效的HTML标记名,并抛出一个无用的错误。

为了解决这个问题,将CustomTag转换为JSX.IntrinsicElements的键!

// var name must start with a capital letter
const CustomTag = `h${this.props.level}` as keyof JSX.IntrinsicElements;

<CustomTag>Hello</CustomTag>