【问题标题】:Apply same styling on multiple elements in component对组件中的多个元素应用相同的样式
【发布时间】:2018-02-04 19:16:43
【问题描述】:
const GreenRow = styled.div`
  background-color: green;
`
const RedRow = styled.div`
  background-color: red;
`
const YellowRow = styled.div`
  background-color: yellow;
`
const GreyRow = styled.div`
  background-color: grey;
`

const MyComponent = () =>
  <div>
    <GreenRow>Green row</GreenRow>
    <div>Blue row</div>
    <RedRow>Red row</RedRow>
    <YellowRow>Yellow row</YellowRow>
    <GreyRow>Grey row</GreyRow>
  </div>

我正在使用styled-components 为组件中的元素设置样式。

我想在组件中的某些元素上应用重复的样式(例如font-weight)。其中一些组件已经使用styled-component 设置样式,所以这将是某种“第二维”样式。

例如,如果我可以使用某个类名定义样式,那么我可以将该类名应用于每个元素。但作为I've understoodstyled-components 不返回任何类名。而且我不想开始在组件本身之外的其他文件中定义样式。

另一个想法是使用 styled-component 的 css 库(参见下面的代码)呈现样式并将其包含在每个适用的 styled-component 定义中。但是为了这个目的,我需要将一些元素转换为样式化组件(因为它们没有其他样式)。

const FontWeight = css`
  font-weight: 600;
`

应用这种“二次元”样式最简洁的方法是什么?

【问题讨论】:

  • 看起来好像您正在定义自定义 HTML 元素。为什么不简单地制作具有共享类的行?就像不是&lt;GreenRow&gt;Green row&lt;/GreenRow&gt;,您可以使用&lt;div class="green row"&gt;Green row&lt;/div&gt;,然后在.row 上设置共享样式,在.green 上设置独特样式?
  • 也许我并不清楚这一点,但我很想继续使用styled-components
  • 您仍然可以使用${props =&gt; props.component_name &amp;&amp; css } 应用相同的概念。
  • 有趣!您能否提供该解决方案作为答案?

标签: css reactjs styled-components


【解决方案1】:

您可以在模板文字中插入一个函数,该模板文字通过 ${props =&gt; props.component_name &amp;&amp; css ... } 传递组件的 props

在下面,我连接到Row 并为Green 添加一些额外的样式:

import styled, { css } from styled-components

const Row = styled.div`
  /* Generic row styling */
  font-weight: 600;

  /* Unique row styling */
  ${props => props.Green && css`
    background: green;
  `}

`

请注意,您还需要导入css

现在你要做的就是在你想要一个绿色的时候渲染带有附加属性的行:

render(
  <div>
    <Row>Normal Row</Row>
    <Row Green>Green Row</Row>
  </div>
);

绿色行将继承常规行的所有样式,并继承该特定元素独有的规则。

希望这会有所帮助!

【讨论】:

  • 很好的答案!我认为应该在 styled-components 文档中描述这种技术!
猜你喜欢
  • 1970-01-01
  • 2020-08-14
  • 1970-01-01
  • 2019-04-18
  • 1970-01-01
  • 1970-01-01
  • 2021-10-30
  • 1970-01-01
相关资源
最近更新 更多