CSS-IN-JS study notes

CSS-IN-JS study notes

Article source: Lagou big front-end high-paying training camp

Integrate CSS code in JS file

1. Why is there CSS-IN-JS

CSS-IN-JS is a solution for bundling CSS code in JS code in WEB projects. This solution aims to solve the limitations of CSS, such as lack of dynamic functions, scope and portability.

2. Introduction to CSS-IN-JS

Advantages of CSS-IN-JS solution:

  1. Let the CSS code have an independent scope, prevent the CSS code from leaking to the outside of the component, and prevent style conflicts.
  2. Make components more portable, implement out-of-the-box use, and easily create loosely coupled applications.
  3. Make components more reusable. You only need to write them once and run anywhere. Not only can you reuse components in the same application, but you can also reuse components in other applications built with the same framework.
  4. Let the style have dynamic functions, you can apply complex logic to the style rules, if you want to create a complex UI that requires dynamic functions, it is an ideal solution.

3. Emotion library

3.1 Introduction to Emotion

Emotion is a library designed to write CSS styles using JS

npm install @emotion/core @emotion/styled

3.2 css attribute support

  1. JSX Pragma

Inform Babel that it is no longer necessary to convert jsx syntax to React.createElement method, but to jsx method.

/** @jsx jsx */
import {
    
     jsx } from '@emotion/core'
  1. Babel Preset
npm run eject
npm install @emotion/babel-preset-css-prop

Find the babel attribute in the package.json file and add the following content:

"presets": [
  "react-app",
  "@emotion/babel-preset-css-prop"
]

Guess you like

Origin blog.csdn.net/jal517486222/article/details/112257172