What is CSS – in – JS
Use CSS like JS. There are two kinds of manifestations:
css
I’m going to write it the same way, butjs
Referable, callable (css Module
);- use
js
To writecss
, more flexible (JSS
/styled-components
).
Why csS-in-JS
Why csS-in-JS? Maybe it solves some of the pain points of CSS and brings some obvious fun points.
-
scope
In general, styles are global in scope, but we are modular, componentized, and want styles to be valid within the scope of the current module/component without affecting other modules/components/global styles.
Scoped is used in Vue so that the style of the current component does not affect other scopes.
We can also use a class selector /ID selector to wrap the current style around it, limiting the style.
-
Potential dependent
Multiple style rules may be superimposed on the same element. The definition of a style rule may contain style rules for multiple elements.
What actually is CSS-in-JS?
-
A CSS rule includes multiple selectors to target different HTML elements.
-
Multiple class names or other attributes are applied to HTML elements, causing them to be targeted by multiple CSS rules.
-
-
Dead code
CSS can be reused, but in the process, some styles may not be desired/effective by the target element. In this case, the extra/invalid code is useless code.
-
The loading sequence is affected
Page A and page B both have the same class selector, but the style Settings are different. First enter the page A, cssA file download, and then enter the page B, cssB file download, also function. At this point, the page is normal. But when I return to page A, I find that the style of page A is wrong because the style defined in cssB overwrites the one defined in cssA. This is the style effect of the loading order.
-
1 Dependence on many
The same style rule may apply to more than one element. If you want to change this style rule, it can be very costly.
-
Higher maintainability
Style rules are defined in small granularity (elements), in small scope (components), and written/imported using JS. The hierarchy is more obvious than CSS writing.
-
More flexibility
The use of JS preparation, can introduce variables, the use of methods, according to the implementation of the environment, flexibility can be imagined.
All of these might be reasons why you want to use CSS-in-JS. To summarize, make style rules more granular and specific; Promote component reuse (that is, element + style) rather than style reuse; Better maintainability and flexibility.
How to use
Different libraries use different methods. Such as:
CSS Module:
The.css file is still needed, and CSS-in-js is bland.
// app.css. TXT {color: '#f00'; } // app.js import React from 'react'; import style from './app.css'; Export default () => (<p className={style.txt}>hello</p>) // Compilation tool < H1 class=" _3ZYDE4L1YATCOKGN-dbwel "> Hello World after compilation </h1> // app.css ._3zyde4l1yATCOkgn-DBWEL { color: red; }Copy the code
JSS:
The.css file is dead and represented by a JSON object. You can pull it out, but when you pull it out, you convert.css to.js.
// The code comes from https://cssinjs.org/?v=v10.5.0 import React from 'React' import {render} from 'React -dom' import {createUseStyles} from 'react-jss' const useStyles = createUseStyles({ myButton: { color: 'green', margin: { // jss-expand gives more readable syntax top: 5, // jss-default-unit makes this 5px right: 0, bottom: 0, left: '1rem' }, '& span': { // jss-nested applies this to a child span fontWeight: 'bold' // jss-camel-case turns this into 'font-weight' } }, myLabel: { fontStyle: 'italic' } }) const Button = ({children}) => { const classes = useStyles() return ( <button className={classes.myButton}> <span className={classes.myLabel}>{children}</span> </button> ) } const App = () => <Button>Submit</Button> render(<App />, document.getElementById('root'))Copy the code
Styled – components:
The most popular CSS-in-JS library. The method of use is unique.
const Button = styled.button`
color: '#f00'
`;
function Temp() {
return <Button />;
}
Copy the code
Styled – Components Method Implementation principle
Styled components Look first at a simple use of the styled components:
const Button = styled.button` color: '#f00' `;
Copy the code
The trick here is: hello(‘world’) == hello ‘world’ (only the call is similar, not congruent).
so
const Button = styled.button` color: '#f00' `;
/ / is equivalent to
const Button = styled.button(["color: '#f00'"["color: '#f00'"]]);
Copy the code
Why does hello(‘world’) == hello ‘world’?
From the AST, **hello ‘world** is also an expression (TaggedTemplateExpression). So no wonder weird statements like this can be executed.
For the Styled components, there are, of course, many other functions, such as:
const Button = styled.button` color: {props => props.color ? props.color : '#f00'} `;
Copy the code
Styled components can be used as styled. Button ‘… ‘such a call way to call just.
There are many more details to learn.
reference
- JSS cssinjs.org/?v=v10.5.0
- styled-components styled-components.com/docs/basics
- TaggedTemplateExpression github.com/estree/estr…
- astexplorer.net/
- What actually is CSS-in-JS? Medium.com/dailyjs/wha…