styled-components https://styled-components.com/
什么是styled-components?
styled-components is the result of wondering how we could enhance CSS for styling React component systems. By focusing on a single use case we managed to optimize the experience for developers as well as the output for end users.
怎么用?
// Create a Title component that'll render an <h1> tag with some styles
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
// Create a Wrapper component that'll render a <section> tag with some styles
const Wrapper = styled.section`
padding: 4em;
background: papayawhip;
`;
// Use Title and Wrapper like any other React component – except they're styled!
render(
<Wrapper>
<Title>
Hello World!
</Title>
</Wrapper>
);
The preprocessor we use, stylis, supports scss-like syntax for automatically nesting styles.
浏览器上展示的
每个对应的Styled component都会被解析成一个唯一的classname,避免重复
Props:
No class name bugs: styled-components generates unique class names for your styles. You never have to worry about duplication, overlap, or misspellings.
-
Simple dynamic styling: adapting the styling of a component based on its props or a global theme is simple and intuitive without having to manually manage dozens of classes.
For the theme part please refer here:https://styled-components.com/docs/advanced#theming Painless maintenance: you never have to hunt across different files to find the styling affecting your component, so maintenance is a piece of cake no matter how big your codebase is.
-
Easy to extend style:
Automatic vendor prefixing: write your CSS to the current standard and let styled-components handle the rest. You get all of these benefits while still writing the CSS you know and love, just bound to individual components.
No Globally Scoped Selectors
One of the most significant benefits of using styled-components, in my opinion, is no longer having to worry about your selector names existing in a global scope with cascading overrides.
Cons:
- Integration With Legacy CSS project Can Be Painful.
。intergrate with the legacy CSS which uses the CSS Module or any other system - Performance issue
styled-components converts all of the style definitions in your React component into plain CSS at build time and the inject everything into the <style> tags in the head of your index.html file. This affects performance in the sense that it is not only increasing the size of our HTML file which can have an impact on the load time, but there is also no way to chunk the output CSS either.
One way to ease this issue slightly is utilizing code-splitting in your app (check out react-loadable or React Code Splitting ) - because
styled-components
happens in JS land, code-splitting ensures only the styles & javascript that are necessary for the current page are sent down to the browser, and the rest can be lazily fetched as the user navigates around.