【问题标题】:How to add custom styled to a styled component?如何将自定义样式添加到样式组件?
【发布时间】:2021-06-12 09:33:58
【问题描述】:

我有一个样式组件<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'`) 似乎应该可以工作,尽管它应该是const Loader = styled(Icon)` font-size:'inherit'`,因为您要返回一个 React 组件。你有什么问题?

标签: reactjs user-interface styled-components css-in-js


【解决方案1】:

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

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

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

<Loader type="loader" />

你也可以在定义Loader时指定type属性:

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

用法:

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

演示

演示代码:

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>

【讨论】:

    猜你喜欢
    • 2020-07-12
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 2019-10-11
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    相关资源
    最近更新 更多