【问题标题】:use styled-components to share styles between components/elements使用 styled-components 在组件/元素之间共享样式
【发布时间】:2020-09-21 10:06:50
【问题描述】:

我正在与 Gatsby 一起使用 styled-components。我使用 styled-components 为 Gatsby 为我的主页提供的 Link 组件设置样式。

const HomePageLink = styled(Link)`
  display: inline-block;
  font-size: ${fontSizes.xxlarge};
  text-decoration: none;
  box-shadow: none;
  :link,
  :visited {
    color: ${colors.slate};
  }
  :hover,
  :active {
    color: ${colors.red};
  }
`

但是我意识到我还需要使用完全相同的样式设置纯 html <a /> 标签的样式。我想知道有没有办法让上面的样式组件适应<a />标签,而无需像这样复制代码

const HomePageAnchorTag = styled.a`
  display: inline-block;
  font-size: ${fontSizes.xxlarge};
  text-decoration: none;
  box-shadow: none;
  :link,
  :visited {
    color: ${colors.slate};
  }
  :hover,
  :active {
    color: ${colors.red};
  }
`

【问题讨论】:

    标签: javascript css reactjs gatsby styled-components


    【解决方案1】:

    是的,使用css API,它允许您构建可重用的 CSS 块。

    一个辅助函数,用于从带有插值的模板文字生成 CSS。

    import styled, { css } from 'styled-components';
    const reusableCSS = css`
      display: inline-block;
      font-size: ${fontSizes.xxlarge};
      text-decoration: none;
      box-shadow: none;
      :link,
      :visited {
        color: ${colors.slate};
      }
      :hover,
      :active {
        color: ${colors.red};
      }
    `;
    
    const HomePageAnchorTag = styled.a`
      ${reusableCSS}
    `;
    
    const HomePageLink = styled(Link)`
      ${reusableCSS}
    `;
    

    通常,您会注意到一个 mixins.js 文件,其中包含可重复使用的 css 块的导出,例如:

    // mixins.js
    const flexCenter = css`...`
    export default { flexCenter };
    
    // usage inside styled components.
    ${mixins.flexCenter}
    

    【讨论】:

      猜你喜欢
      • 2021-08-26
      • 2019-02-09
      • 2019-12-21
      • 2019-12-21
      • 1970-01-01
      • 2021-12-28
      • 2021-12-06
      • 2021-06-02
      • 2019-09-10
      相关资源
      最近更新 更多