如何将自定义样式添加到样式组件?

问题描述

我有一个样式组件 <Icon type="loader"/>。我想通过向这个 Icon 组件添加一些自定义样式来创建另一个样式组件。我需要将 type 传递给 Icon 组件,我该如何实现?

const loader = styled(Icon)` font-size:'inherit'`

在没有任何道具的情况下直接传递图标工作正常。

我试过这个: const CustomIcon = () => <Icon type="loader"/>

const loader = styled(CustomIcon)` font-size:'inherit'`

这会出错。

解决方法

我认为你的第一种方式就足够了。

const Loader = styled(Icon)`
  font-size: inherit;
`;

您可以将 type="loader" 传递给 Loader

<Loader type="loader" />

您还可以在定义 type 时指定 Loader 属性:

const Loader = styled(Icon).attrs(() => ({
  type: 'loader',}))`
  font-size: inherit;
`;

用法:

<Loader /> // type="loader" passed to styled Icon

演示

Edit how-to-add-custom-styled-to-a-styled-component

演示代码:

const Icon = styled(({ type,...props }) => {
  switch (type) {
    case "loader":
      return <div {...props} className={props.className + " loader"} />;

    default:
      return <div {...props} />;
  }
})`
  font-size: 3rem;

  &.loader {
    color: red;
  }
`;

const Loader = styled(Icon).attrs(() => ({
  type: "loader"
}))`
  font-size: initial; // overrides Icon fontsize
`;

...

<Icon>Test</Icon>
<Icon type="loader">Test</Icon>
<Loader>Test</Loader>

enter image description here