This article is intended to explain csS-in-JS as part of the 2020 CSS Peripheral: Preprocessor, CSS-In-JS, and other solutions and methodologies
What is styled – components
Styled – Components is a JS library, hereinafter referred to as SC, which provides an API for writing CSS to enhance the styling functionality of the React component system. Other CSS-IN-JS solutions take a similar approach.
The basic usage is as follows
// Create a component import Styled from 'property-components '; Style = styled. H1 'font: styled; `; // Use render(<Title> Hello World! </Title> );Copy the code
After processing CSS, SC provides us with the following
- Tracking the auto-injection styles of components rendered on the page, combined with code splitting, loads as little code as possible.
- Generate unique class names without worrying about duplication and overwriting, which is what CSS-modules are designed to do
- It can be very clear which code is using the specified style, change or delete easy maintenance
- Set styles dynamically based on props or global variables
- Automatically add browser-specific prefixes
The basic principle of
If you want to learn a JS library, it is more important to understand its principles than to use them, and to use apis that are only exposed on the basis of calling principles, so here is a brief introduction to the basic implementation.
First, styled. H1 ‘ ‘syntax is called Tagged Template Literal, similar to The direct function call, styled. H1 () (for details in SC see The magic behind 💅 styled-components), It is essentially a component factory that returns various components with our own custom styles.
When React starts rendering the component, calling Styled. H1, This is equivalent to executing the Style executive (‘ H1 ‘)([style])(because the corresponding method is mounted to it during Styled initialization), and then generating the component for React through a series of steps by calling the createStyledComponent method.
During component creation
- To calculate tagged template, obtain
componentStyle
- According to the
componentId
andcomponentStyle
Such as calculating the className - Use STYLIS to preprocess styles with browser prefixes
- Add the generated style to the style tag
- Create an element corresponding to className
With a simple analysis of the SC, we have a rudimentary understanding of its execution, and now let’s look at its usage
guide
The basic use
In addition to the usage described above
The use of props
You can add a function interpolation where the parameter is props, for example
const Button = styled.button`
/* Adapt the colors based on primary prop */
background: ${props => props.primary ? "palevioletred" : "white"};
color: ${props => props.primary ? "white" : "palevioletred"};
`;
render(
<div>
<Button>Normal</Button>
<Button primary>Primary</Button>
</div>
);
Copy the code
Extension style
Build one component from another, and the base component can be any component
// Style is a component const TomatoButton = Styled (Button) 'color: tomato; border-color: tomato; `;Copy the code
Styles from CSS
You can import styles from the CSS file for use, just as you can with the cssModule
import styles from './styles.css'
<h1 className="title">
Hello World
</h1>
Copy the code
//styles.css
.title {
color: red;
}
Copy the code
Pseudo classes, pseudo elements, and nesting
Sc-dependent stylis can provide a sass-like syntax to provide this functionality. (For a review of sASS syntax, please refer to the sASS Usage Guide around CSS 2020.)
Add additional or rewrite props
Add additional props using the.attrs method
const Input = styled.input.attrs(props => ({
// we can define static props
type: "text",
// or we can define dynamic ones
size: props.size || "1em",
}))`
padding: ${props => props.size};
`;
render(
<div>
<Input placeholder="A small text input" />
<br />
<Input placeholder="A bigger text input" size="2em" />
</div>
);
Copy the code
Some skills
- Override styles with high priority
const MyStyledComponent = styled(AlreadyStyledComponent)`
&&& {
color: palevioletred;
font-weight: bold;
}
`
Copy the code
Each ampersand generates a class, such as
.MyStyledComponent-asdf123.MyStyledComponent-asdf123.MyStyledComponent-asdf123 {
color: palevioletred;
font-weight: bold;
}
Copy the code
- Override inline styles
const MyStyledComponent = styled(InlineStyledComponent)` &[style] { font-size: 12px ! important; color: blue ! important; } `Copy the code
conclusion
SC is a JS library with very little content compared to sASS, a language-level tool. Please refer to the SC official documentation for more usage. Now you can continue to read about CSS in 2020: Preprocessor, CSS-In-JS, and other parts of the methodology 🎨!