【问题标题】:What is the best way to apply layout styling to styled-components and React components used in different places on a site?将布局样式应用于站点上不同位置的样式组件和 React 组件的最佳方法是什么?
【发布时间】:2020-01-12 07:44:10
【问题描述】:

我有整个网站都在使用的 React 组件和样式化组件。例如,按钮和卡片。我听说使用内联样式是一种代码味道,应该避免。

然而,为了让东西看起来更漂亮,css(尤其是边距、内边距和尺寸)仍然需要根据具体情况应用到组件。

我可以看到许多选项:

  • 创建复合组件,每个组件用于不同的地方,例如 Card, Card.Padded, Card.Large
  • 创建(可能多个)具有不同基于的新组件 使用样式组件的“基础”组件,例如styled(Card) 创建 CardCharacters CardHomePage 等

  • 在需要不同样式的地方使用 props 改变样式 例如<Card withSomeMargins /><Card margin={big} />

  • 在每个页面上使用不同的 ThemeProvider 将样式应用于 组件

谁能就哪种方法是“最佳实践”或首选方法提供任何建议?我知道不同的方法可能更适合不同的情况,可能没有“最佳”方法,但我很想听听人们的想法。

【问题讨论】:

    标签: css reactjs components styling styled-components


    【解决方案1】:

    “最好”的方法是使用道具来改变样式。并不是因为它在一般情况下使用 CSS-in-JS 是一种更好的做法,而是因为这是 Styled Components 设计的方法。当然,如果你发现你在 props 的基础上改变了太多,你应该把它拆分成一个新的样式组件。所以答案是你的第二点和第三点的混合。

    避免通过 props 传递特定样式值(如 width="100%"),而是传递标志或对象键以从主题中获取所需的值。

    此外,您可能会发现过多的道具插值会导致样式的可读性降低。这种方法可以让它更好一点:

    export const Card = styled.div(({ theme, margin }) => css`
      margin: ${margin ? theme.margin[margin] : 0};
      font-family: ${theme.font};
      font-size: ${theme.sizeBig};
      color: ${theme.dark};
      font-weight: ${theme.fontWeight}
    `)
    

    【讨论】:

      猜你喜欢
      • 2019-08-23
      • 2020-05-27
      • 2020-10-18
      • 1970-01-01
      • 2019-02-14
      • 1970-01-01
      • 2022-06-24
      • 2019-09-26
      • 2016-06-14
      相关资源
      最近更新 更多