243

我正在尝试为 HTML 标题标签(、、、等)编写一个 React 组件h1h2其中h3标题级别是通过道具指定的。

我试着这样做:

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

和预期的输出,如:

<h1>Hello</h1>

但这不起作用。有没有可能的方法来做到这一点?

4

8 回答 8

460

无法就地执行此操作,只需将其放入变量中(首字母大写):

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

<CustomTag>Hello</CustomTag>
于 2015-11-02T06:31:11.033 回答
94

如果您使用的是 TypeScript,您会看到如下错误:

Type '{ children: string; }' has no properties in common with type 'IntrinsicAttributes'.ts(2559)

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

要修复,请转换CustomTagkeyof JSX.IntrinsicElements!

const CustomTag = `h${this.props.level}` as keyof JSX.IntrinsicElements;

<CustomTag>Hello</CustomTag>
于 2020-01-10T16:57:07.570 回答
44

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

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

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

带道具:

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

文档

创建并返回给定类型的新 React 元素。type 参数可以是标签名称字符串(例如'div''span'),也可以是 React 组件类型(类或函数)。

使用 JSX 编写的代码将转换为使用React.createElement(). React.createElement()如果您使用 JSX,通常不会直接调用。请参阅没有 JSX 的 React以了解更多信息。

于 2017-08-21T02:27:27.117 回答
16

所有其他答案都工作正常,但我会添加一些额外的,因为这样做:

  1. 它更安全一些。即使您的类型检查失败,您仍然会返回正确的组件。
  2. 它更具声明性。通过查看此组件的任何人都可以看到它可以返回什么。
  3. 它更灵活,例如代替'h1','h2',......对于你的标题类型,你可以有一些其他抽象概念'sm','lg'或'primary','secondary'

标题组件:

import React from 'react';

const elements = {
  h1: 'h1',
  h2: 'h2',
  h3: 'h3',
  h4: 'h4',
  h5: 'h5',
  h6: 'h6',
};

function Heading({ type, children, ...props }) {    
  return React.createElement(
    elements[type] || elements.h1, 
    props, 
    children
  );
}

Heading.defaultProps = {
  type: 'h1',
};

export default Heading;

你可以像这样使用它

<Heading type="h1">Some Heading</Heading>

或者你可以有一个不同的抽象概念,例如你可以定义一个尺寸道具,如:

import React from 'react';

const elements = {
  xl: 'h1',
  lg: 'h2',
  rg: 'h3',
  sm: 'h4',
  xs: 'h5',
  xxs: 'h6',
};

function Heading({ size, children }) {
  return React.createElement(
    elements[size] || elements.rg, 
    props, 
    children
  );
}

Heading.defaultProps = {
  size: 'rg',
};

export default Heading;

你可以像这样使用它

<Heading size="sm">Some Heading</Heading>
于 2019-06-02T00:31:36.407 回答
6

在动态标题(h1, h2...)的实例中,组件可以像这样返回React.createElement(上面由Felix提到)。

const Heading = ({level, children, ...props}) => {
    return React.createElement(`h${level}`, props , children)
}

为了可组合性,props 和 children 都被传递。

查看示例

于 2018-06-14T21:51:17.440 回答
2

你可以试试这个。我是这样实现的。

import { memo, ReactNode } from "react";
import cx from "classnames";

import classes from "./Title.module.scss";

export interface TitleProps {
  children?: ReactNode;
  className?: string;
  text?: string;
  variant: Sizes;
}

type Sizes = "h1" | "h2" | "h3" | "h4" | "h5" | "h6";
const Title = ({
  className,
  variant = "h1",
  text,
  children,
}: TitleProps): JSX.Element => {
  const Tag = `${variant}` as keyof JSX.IntrinsicElements;
  return (
    <Tag
      className={cx(`${classes.title} ${classes[variant]}`, {
        [`${className}`]: className,
      })}
    >
      {text || children}
    </Tag>
  );
};

export default memo(Title);
于 2021-06-02T10:33:42.880 回答
0

这就是我为我的项目设置它的方式。

排版类型.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';
};

排版.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;
于 2021-10-17T05:55:59.167 回答
0

概括robstarbuck 的答案,您可以创建一个完全动态的标签组件,如下所示:

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

你可以像这样使用:

const App = ({ myTagName = 'h1' }) => {
  return (
    <Tag tagName={myTagName} className="foo">
     Hello Tag!
    </Tag>
  )
}
于 2022-01-03T09:44:52.210 回答