如何从外部替换React组件中渲染的HTML元素

91 阅读1分钟

在使用现代UI组件库时,你可能已经注意到 "as "道具。从本质上讲,"as "道具允许你从外部替换React组件中渲染的HTML元素,将它们作为道具传入

const Headline = ({ as = 'h1', children }) => {
  const As = as;
  return <As>{children}</As>;
};

const App = () => {
  return (
    <>
      <Headline>Hello React</Headline>
      <Headline as="h2">Hello React</Headline>
    </>
  );
};

通常它被称为 "as "道具,然而,我们也可以把它看作是 "组件"、"元素"、"变体 "道具--或者其中两个的组合。例如,使用 "组件 "和 "变体 "道具组合的一个用例是这样的。

const Headline = ({ component, variant, children }) => {
  const Component = component;
  return <Component className={variant}>{children}</Component>;
};

const App = () => {
  return (
    <main>
      <div>
        <Headline component="h1" variant="h1">
          Web Development Explained
        </Headline>
      </div>
      <div>
        <Headline component="h2" variant="h1">
          React Explained
        </Headline>
      </div>
    </main>
  );
};

在这个例子中,我们为一篇文章的两个部分设置了两个标题。虽然两个标题在文章中看起来是一样的(变体),但它们在语义上应该是不同的(组件),因为页面上只能有一个h1的HTML元素。

如果你想在变体、组件或作为道具使用TypeScript,请查看以下代码片段。

interface HeadlineProps {
  component: React.ElementType;
  variant: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6';
  children: React.ReactNode;
}

const Headline: React.FC<HeadlineProps> = ({
  component,
  variant,
  children,
}) => {
  const Component = component;
  return <Component className={variant}>{children}</Component>;
};

就这样了。特别是当你在创建内部UI组件库或设计系统时,在处理语义和美学的组合时,这些道具变得很重要。