假设您正在使用 react 构建一个可重用的 <section> 组件。该部分组件呈现一个 html <div> 标记,因为您对其进行了硬编码。 但是,在某些情况下,您可能想使用其他标签,例如 <section> html 标签。
这是一个典型的场景,当您希望 html 更加语义化并且 seo 友好时。
解决方案是让消费者决定应该使用哪个 html 标签来呈现组件。
这不是什么新鲜事。
这是一种行业标准“方法”,允许您动态决定应该使用哪个 html 标签来呈现组件。很多 react components 库都使用它,比如 chakra ui 和 material ui。
如果没有“as”属性,您需要为每个用例创建单独的组件,这是没有意义的。别这样做!
这就是你使用“as”属性的方式
import { section } from './section';
const app = () => {
return (
<div>
<section as="section">cta</section>
<section as="article">my article</section>
<section>this use the default html tag of the component</section>
</div>
);
};
这是组件定义
type sectionprops = {
as?: react.elementtype,
children: react.reactnode,
}
export const section = (props: sectionprops) => {
const { as: tag = 'div', children } = props;
return <tag>{children}</tag>;
}
react 帮助我们处理 typescript 类型。
使用 react 提供的打字稿的 react.elementtype 类型,您将为您的 ide 获得自动完成功能,如下所示

立即学习“前端免费学习笔记(深入)”;
作为 react.elementtype 的替代品,您可以使用
type sectionprops = {
as?: keyof jsx.intrinsicelements,
children: react.reactnode,
}
或
type SectionProps = {
as?: keyof HTMLElementTagNameMap,
children: React.ReactNode,
}
以上就是React 组件中带有“as”属性的动态 HTML 标签的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号