样式组件局部变量
styled-components local variable
来自 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...
}
目前 styled-component (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
问题是,我想将 "meaningless" size
变量保留在使用它的同一上下文中(就像在 SCSS 中一样),因为没有别的关心或将永远关心它。我不认为将变量转储到某处然后将其与 '${size}'
一起使用是一种 "clean" 方式。这种策略是琐碎的,并且会导致代码库混乱。
我想出了一个巧妙的技巧来封装特定范围内的变量:
styled.h1(({size='4em', color='lime'}) => `
font-size: ${size};
color: ${color};
text-align: center;
`)
我以前写过一篇Medium post,分解了这个方法的解释
解决此问题的一种方法是创建一个单独的文件,其中包含您稍后要在样式文件中使用的所有变量:
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);
}
来自 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...
}
目前 styled-component (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
问题是,我想将 "meaningless" size
变量保留在使用它的同一上下文中(就像在 SCSS 中一样),因为没有别的关心或将永远关心它。我不认为将变量转储到某处然后将其与 '${size}'
一起使用是一种 "clean" 方式。这种策略是琐碎的,并且会导致代码库混乱。
我想出了一个巧妙的技巧来封装特定范围内的变量:
styled.h1(({size='4em', color='lime'}) => `
font-size: ${size};
color: ${color};
text-align: center;
`)
我以前写过一篇Medium post,分解了这个方法的解释
解决此问题的一种方法是创建一个单独的文件,其中包含您稍后要在样式文件中使用的所有变量:
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);
}