样式组件局部变量



来自SCSS(SASS(

以下SCSS代码的适当样式组件实现是什么?

scs:

.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}'一起使用是一种"干净"的方式。这样的策略很琐碎,而且会导致代码库混乱。

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

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

我过去写过一篇Medium帖子,对这种方法的解释进行了分解

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

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%;
`

您可以像这样使用经典的css属性(考虑到IE11 polyfill(:

--radioWidth: 42px;  
.MuiRadio-root {
width: var(--radioWidth);
}
.conditionCollapse {
padding-left: var(--radioWidth);
}

最新更新