前提条件
请先进行全局安装 create-react-app 插件哈,安装命令:npm install create-react-app -g
先使用 create-react-app 命令下载一个脚手架工程,安装命令:
# 使用 npx $ npx create-react-app my-app # 使用 npm $ npm init npx create-react-app my-app # 使用 yarn $ yarn create react-app my-app
运行项目
$ cd my-app # 使用 npm $ npm start # 或者使用yarn # yarn start
在浏览器中输入 http://localhost:3000
查看项目效果
使用 CSS Module 的第一种方式
create-react-app 中内置了使用 CSS Modules 的配置,当前方式就是使用 create-react-app 内置的用法
方式
将所有的 .css/.lee/.scss 等样式文件都修改成 .module.css/.module.less/.module.scss 等。即可使用 CSS Modules 的方式进行引入使用了。
用法
编写一个 css 文件:Button.module.css
.error { background-color: red; }
在编写一个普通的 css 文件:another-stylesheet.css
.error { color: red; }
在 js 文件中使用 CSS Modules 的方式进行引用:Button.js
import React, { Component } from 'react'; import styles from './Button.module.css'; // 使用 CSS Modules 的方式引入 import './another-stylesheet.css'; // 普通引入 class Button extends Component { render() { // reference as a js object return <button className={styles.error}>Error Button</button>; } }
在浏览器中查看效果
此时 Button 组件的背景颜色是红色,但是字体颜色却不是红色,因为使用了 Css Modules 之后,普通的 css 样式就不起效果了,需要用全局的方式编写才可以(:global)。 最后添加到元素上的样式结果为: <button class="Button_error_ax7yz">Error Button</button>
使用 CSS Module 的第二种方式
方式
在命令行运行 npm run eject
命令
此命令会将脚手架中隐藏的配置都展示出来,此过程不可逆
运行完成之后,打开 config 目录下的 webpack.config.js 文件,找到 test: cssRegex
这一行
在 use 属性执行的方法中添加 modules: true
,如下图:
用法
和第一种方式的用法一致,只是不需要在 css 文件后面加 .module 后缀了
编写一个 css 文件:Button.css
.error { background-color: red; }
再编写一个普通的 css 文件:another-stylesheet.css
.error { color: red; }
在 js 文件中使用 CSS Modules 的方式进行引用:Button.js
import React, { Component } from 'react'; import styles from './Button.css'; // 可以直接使用 CSS Modules 的方式引入了 import './another-stylesheet.css'; // 普通引入 class Button extends Component { render() { // reference as a js object return <button className={styles.error}>Error Button</button>; } }
在浏览器中查看效果
此时 Button 组件的背景颜色是红色,但是字体颜色却不是红色,因为使用了 Css Modules 之后,普通的 css 样式就不起效果了,需要用全局的方式编写才可以(:global)。 最后添加到元素上的样式结果为: <button class="Button_error_ax7yz">Error Button</button>
如想使用第二种方式对 sass 和 less 也使用 CSS Modules 的方式进行引用,则类似的在 sass 和 less 解析配置上也添加modules: true 即可。
注意
默认 create-react-app 脚手架不能直接使用 sass 和 less 直接编写 css,需要先进行相应配置。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
更新日志
- 华少翌.2005-华少翌【中唱艺能】【WAV+CUE】
- 群星《十二女声Ⅱ》[WAV/CUE/分轨][527MB]
- 大自然音乐系列《漫步在山裡》[WAV/CUE/分轨][502.8MB]
- 大自然音乐系列《星光夜语》[WAV/CUE/分轨][453.3MB]
- 史依弘《史依弘交响乐京剧演唱专辑HQ》头版限量编号[WAV+CUE]
- 曼丽2020《女人三十风继续吹》HQCD[WAV+CUE]
- 曼丽2021《女人三十2雾之恋》HQCD[WAV+CUE]
- 隔壁老樊.2019-我曾【好听音乐】【FLAC分轨】
- 高林生.1993-牵挂你的人是我【白天鹅】【WAV+CUE】
- 洪卓立.2012-找个懂我的女孩(国专)【英皇娱乐】【WAV+CUE】
- 曼丽2022《女人三十3晚秋》HQCD[WAV+CUE]
- 曼丽2018《女人三十4冬天》HQCD[WAV+CUE]
- 柏菲-《好歌30年壹》限量开盘母带ORMCD[低速原抓WAV+CUE]
- 大自然音乐系列《水舞》[WAV/CUE/分轨][424.3MB]
- 大自然音乐系列《星光夜语》[WAV/CUE/分轨][453.3MB]