首页 > 文章列表 > React 组件中带有“as”属性的动态 HTML 标签

React 组件中带有“as”属性的动态 HTML 标签

141 2025-01-12

假设您正在使用 react 构建一个可重用的 <section> 组件。该部分组件呈现一个 html <div> 标记,因为您对其进行了硬编码。 但是,在某些情况下,您可能想使用其他标签,例如 <section> html 标签。

这是一个典型的场景,当您希望 html 更加语义化并且 seo 友好时。

解决方案是让消费者决定应该使用哪个 html 标签来呈现组件。

“as” 道具

这不是什么新鲜事。

这是一种行业标准“方法”,允许您动态决定应该使用哪个 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>;

}

typescript 对“as”属性的支持

react 帮助我们处理 typescript 类型。

使用 react 提供的打字稿的 react.elementtype 类型,您将为您的 ide 获得自动完成功能,如下所示

React 组件中带有“as”属性的动态 HTML 标签

作为 react.elementtype 的替代品,您可以使用

type sectionprops = {
  as?: keyof jsx.intrinsicelements,
  children: react.reactnode,
}


type SectionProps = {
  as?: keyof HTMLElementTagNameMap,
  children: React.ReactNode,
}
来源:https://dev.to/tresorama/dynamic-html-tag-in-react-components-with-the-as-prop-56b8

本类最新

查看更多