首页 > 解决方案 > styled-component 生成自定义 css 类

问题描述

我有一个关于styled-components图书馆的问题。我知道这可能不是一种惯用的做事方式,但我很好奇是否有可以返回 CSS 类名的 styled-component 方法。然后我可以将该类名传递给我渲染的组件。这样,我可以重用一些 CSS。再说一次,也许这违背了将隔离样式限定为单个组件的目的。

例如,是否有类似的功能generateCss

const Button = styled.div`
  background-color: blue;
`

const myCssClassName = styled.generateCss`
    background-color: blue;
`
...
<Button className={myCssClassName} />

标签: reactjsstyled-components

解决方案


如果你想自定义一个现有的样式组件,你可以使用.extend()API

例如:

const Button = styled.div`
  background-color: red;
`;

const BlueButton = Button.extend`
  background-color: blue;
`;

export default () => (
  <BlueButton />
);

推荐阅读