styled-components局部变量

问题描述 投票:0回答:2

来自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...
}

Currently the styled-component (Circle) looks like this:

...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}'一起使用是一种“干净”的方式。这样的策略很小,并且会促进凌乱的代码库。

css reactjs styled-components
2个回答
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
投票

I have devised a neat trick to encapsulate variables only for a specific scope:

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

我过去写了一篇qazxsw poi,它打破了这种方法的解释

© www.soinside.com 2019 - 2024. All rights reserved.