I've been using SCSS
(SASS
) for many years now, and also have been using Styled-Components
for a few projects, some large.
I love both, and Styled-Components
feels, for me, like a step forward:
Styled-Components - Pros
- Total styling isolation; prevents potential bugs when working in teams, when one team member can never override a style of another. (unless multiple places share the same styled component)
- Remove the need to manually handle class names as they get auto-generated (name-picking components is somewhat easier IMHO than class names)
I've found it easier to work with CSS within the JSX file itself (Opposing my judgment for many years before)
Easily use javascript variables within styles (eliminate the need for 2-sets of theme variable)
Styled-Components - Cons
- Each style component is yet another wrapper function, and many styled-components means more functions, which means less efficient since all that code needs to be "compiled" and so on.
- Biggest drawback: changes to styles require bundle re-compilation and the app's state might reset.
The cons can be only viewed as such on some scenarios but not
necessarily all.
SCSS/LESS pros can be viewed as opposite to the cons listed above, while having some more cons such as mixings and faster development when working with variables (IMHO). it can get "ugly" defining a local selector variable:
Compare these simplified examples:
SCSS
example:
.icon{
$size: '20px';
width: $size;
height: $size;
margin-left: $size/2;
}
Styled-Components
local scope example:
const Icon = styled.i(props => {
const size = 20; // easier to use Number instead of String for calculations
return `
width: ${size}px;
height: ${size}px;
margin-left: ${size/2}px;
`});
Obviously the variable could have been defined outside of the Icon
styled wrapper and then internally used, but that won't make it isolated, because styled-component CSS might be composed of sub-components styled and look more like CSS:
const Header = styled.header`
> ul{
...
}
li{
...
}
img{...}
navigation{...}
`
Not always it is desirable to extract each individual HTML element to its own styled component. it is done mostly for components that are or might be repeated across the app.
Regarding SASS mixings, they can be converted to javascript functions, so there's not much advantage to SASS here.
Overall, working with Styled-Components is fun & easy, but has a side-effect of a tighter coupling between the styles and the framework/component and it obviously has some performance penalty (nothing that will actually slow you down, but still).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…