我正在尝试为 HTML 标题标签(、、、等)编写一个 React 组件h1
,h2
其中h3
标题级别是通过道具指定的。
我试着这样做:
<h{this.props.level}>Hello</h{this.props.level}>
和预期的输出,如:
<h1>Hello</h1>
但这不起作用。有没有可能的方法来做到这一点?
无法就地执行此操作,只需将其放入变量中(首字母大写):
const CustomTag = `h${this.props.level}`;
<CustomTag>Hello</CustomTag>
如果您使用的是 TypeScript,您会看到如下错误:
Type '{ children: string; }' has no properties in common with type 'IntrinsicAttributes'.ts(2559)
TypeScript 不知道这CustomTag
是一个有效的 HTML 标记名称,并抛出一个无用的错误。
要修复,请转换CustomTag
为keyof JSX.IntrinsicElements
!
const CustomTag = `h${this.props.level}` as keyof JSX.IntrinsicElements;
<CustomTag>Hello</CustomTag>
为了完整起见,如果要使用动态名称,也可以直接调用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以了解更多信息。
所有其他答案都工作正常,但我会添加一些额外的,因为这样做:
标题组件:
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>
你可以试试这个。我是这样实现的。
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);
这就是我为我的项目设置它的方式。
排版类型.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;
概括robstarbuck 的答案,您可以创建一个完全动态的标签组件,如下所示:
const Tag = ({ tagName, children, ...props }) => (
React.createElement(tagName, props , children)
)
你可以像这样使用:
const App = ({ myTagName = 'h1' }) => {
return (
<Tag tagName={myTagName} className="foo">
Hello Tag!
</Tag>
)
}