添加 CSS 模块样式表
注意:
react-scripts@2.0.0
及更高版本提供此功能。¥Note: this feature is available with
react-scripts@2.0.0
and higher.
该项目支持 CSS 模块 以及使用 [name].module.css
文件命名约定的常规样式表。CSS 模块允许通过自动创建格式为 [filename]\_[classname]\_\_[hash]
的唯一类名来限定 CSS 的范围。
¥This project supports CSS Modules alongside regular stylesheets using the [name].module.css
file naming convention. CSS Modules allows the scoping of CSS by automatically creating a unique classname of the format [filename]\_[classname]\_\_[hash]
.
提示:如果你想使用 Sass 预处理样式表,请确保 按照安装说明进行操作,然后更改样式表文件扩展名,如下所示:
[name].module.scss
或[name].module.sass
。¥Tip: Should you want to preprocess a stylesheet with Sass then make sure to follow the installation instructions and then change the stylesheet file extension as follows:
[name].module.scss
or[name].module.sass
.
CSS 模块让你可以在不同的文件中使用相同的 CSS 类名,而不必担心命名冲突。此处 了解有关 CSS 模块的更多信息。
¥CSS Modules let you use the same CSS class name in different files without worrying about naming clashes. Learn more about CSS Modules here.
Button.module.css
.error {
background-color: red;
}
another-stylesheet.css
.error {
color: red;
}
Button.js
import React, { Component } from 'react';
import styles from './Button.module.css'; // Import css modules stylesheet as styles
import './another-stylesheet.css'; // Import regular stylesheet
class Button extends Component {
render() {
// reference as a js object
return <button className={styles.error}>Error Button</button>;
}
}
结果
¥Result
与其他 .error
类名称没有冲突
¥No clashes from other .error
class names
<!-- This button has red background but not red text -->
<button class="Button_error_ax7yz">Error Button</button>
这是一项可选功能。完全支持常规 <link>
样式表和 CSS 文件。CSS 模块打开为以 .module.css
扩展名结尾的文件。
¥This is an optional feature. Regular <link>
stylesheets and CSS files are fully supported. CSS Modules are turned on for files ending with the .module.css
extension.