样式化组件局部变量

时间:2018-11-16 21:09:31

标签: css reactjs styled-components

来自 SCSS SASS

下面的 SCSS 代码的 Styled-Components 合适的实现是什么?

SCSS:

.circle{
  $size: 16px;  // <-- SCSS FTW. use such a trick in styled-components

  height: $size;
  width: $size;
  .. rest of properties...
}

当前,样式化组件Circle)如下所示:

...lots of other styled exports

export const Circle = styled.div`
  height: 16px;
  width: 16px;
  background: red;
  border-radius: 50%;
`

...lots of other styled exports

问题是,我想在使用该变量的相同上下文中保留该“无意义” size变量(就像在 SCSS 中一​​样),因为没有别的在乎或曾经在意它。我不认为将变量转储到某个地方然后与'${size}'一起使用是一种“干净”的方法。这样的策略是琐碎的,会促进凌乱的代码库。

3 个答案:

答案 0 :(得分:0)

解决此问题的一种方法是创建一个单独的文件,其中包含所有以后要在样式文件中使用的变量:

export const Variables = {
  size: '16px',
  bgColor: 'red',
}

然后您可以导入它:

import { Variables } from './Variables'

export const Circle = styled.div`
  height: ${Variables.size};
  width: ${Variables.size};
  background: ${Variables.bgColor};
  border-radius: 50%;
`

答案 1 :(得分:0)

您可以像这样使用经典的CSS属性(请牢记IE11 polyfill):

fig = plt.figure(facecolor='#131722',dpi=155, figsize=(8, 6))
ax1 = plt.subplot2grid((3,2), (0,0), facecolor='#131722', rowspan=2)
ax2 = plt.subplot2grid((3,2), (0,1), facecolor='#131722', rowspan=2)
ax3 = plt.subplot2grid((3,2), (2,0), facecolor='#131722')
ax4 = plt.subplot2grid((3,2), (2,1), facecolor='#131722')

答案 2 :(得分:-1)

我设计了一个巧妙的技巧,仅针对特定范围封装变量:

styled.h1(({size='4em', color='lime'}) => `
  font-size: ${size};
  color: ${color};
  text-align: center;
`)

我过去写过Medium post,破坏了这种方法的精髓

相关问题