steps
-
Example Run the MPM I sass -d command
-
Change the style file name. From xx.scSS -> xx.module. SCSS (React scaffolding convention, distinguished from normal CSS)
-
Introduce use.
-
Import the style file into the component (note the syntax)
import styles from './index.module.scss' Copy the code
-
Styles are set by accessing the style name in the object via the Styles object
<div className={styles.css className}></div>Copy the code
CSS class names are defined in index.module. SCSS.
-
The sample
The original
- Define the style index.css
.root {font-size: 100px; }Copy the code
- Using styles
Import 'index.css' <div className="root"> contents of div </div>Copy the code
now
Change the file name: index.css —-> index.module. CSS Within the same
Using styles
Import styles from './index.module. CSS '<div className={styles.root}>Copy the code
The principle of
CSS Modules automatically complement CSS class names to ensure that class names are unique and avoid style conflicts.
// Login.jsx
import styles from './index.module.css'
console.log(styles)
Copy the code
Notes on the CSS Module
It is best to use a hump for class names, because eventually the class name generates a property of Styles
.tabBar {} ---> styles.tabBar
Copy the code
If a hyphen is used, the [] syntax is required
.tab-bar {} ---> styles['tab-bar']
Copy the code
CssModules – Maintain the class name
The target
Master the use of the :global keyword to maintain the original class name
format
In xxx.module. SCSS, if you want to maintain the class name, you can use the format:
: global (. The name of the class)
The sample
/* So CSS Modules don't change the class name. A. Equivalent to writing in index.css */ :global(.a) {}Copy the code
*/. Aa :golbal(.a) {}Copy the code
application
Overrides the styles of third-party components
:global(.ant-btn) { color: red ! important; }Copy the code
CSS modules- Best practices
- The root node of each component uses a class name of the form CSSModules (class name of the root element:
root
) - All other child nodes use the normal CSS class name :global
index.module.scss
// index.module.scss .root { display: 'block'; position: 'absolute'; // Here, use global to wrap the class names of other child nodes. In this case, the class names are not processed, and when used in JSX, the class name can be a string, if not :global, Global {.title {.text {} span {}}.login-form {... }}}Copy the code
component
Import styles from './index.module. SCSS 'const component = () => {return ({/* (1) root nodes use CSSModules form class names (root element class names: 'root') */} <div className={styles.root}> {/* (2) all children, Use common CSS class names */} <h1 className="title"> <span className="text"> Login </span> < SPAN > Login </span> </h1> <form className="login-form"></form> </div> ) }Copy the code