react 组件添加样式_如何通过4个简单的步骤将CSS模块样式表添加到React组件

react 组件添加样式

Let’s say you’d like to add a CSS Modules Stylesheet to your project. You can find Create React App’s guidance here, but essentially — and as the guidance states — CSS Modules let you use the same CSS selector in different files without worrying about naming clashes. This works because each HTML element in your file that you want to style is automatically given a unique class name.

假设您要在项目中添加CSS模块样式表。 您可以在此处找到Create React App的指南 ,但从本质上(作为指南的陈述),CSS模块使您可以在不同文件中使用相同的 CSS选择器,而不必担心命名冲突。 之所以可行,是因为您要设置样式的文件中的每个HTML元素都会自动获得一个唯一的类名。

This can seem quite confusing at first, but really the process to implement CSS Modules can be simplified to just 4 steps, as demonstrated in the below example.

乍一看这似乎很令人困惑,但是实际上实现CSS模块的过程可以简化为仅4个步骤,如以下示例所示。

  1. A feature of React is that CSS Modules are “turned on” for files ending with the .module.css extension. Create the CSS file with a specific filename in the following format:

    React的一个功能是,对于以.module.css扩展名结尾的文件,“打开” CSS模块。 使用以下格式创建具有特定文件名CSS文件:

Link.module.css

2. Import styling to your component:

2.将样式导入到您的组件中:

import styles from ‘../styling/components/Link.module.css’

3. The styles in your CSS file can follow your preferred naming convention, for instance:

3. CSS文件中的样式可以遵循您的首选命名约定,例如:

.bold {  font-weight: bold;}

4. The style is applied to the HTML element as follows:

4.将样式应用于HTML元素,如下所示:

className={styles.bold}

And that’s it!

就是这样!

Photo credit: Adrian Swancar on Unsplash

照片来源: Unsplash 上的 Adrian Swancar

翻译自: https://www.freecodecamp.org/news/how-to-add-a-css-modules-stylesheet-to-your-react-component-in-4-simple-steps/

react 组件添加样式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值