我有几个组件具有以下CSS /组件结构
About/style.css
.AboutContainer {
# Some style
}
p > code {
# Some style
}
Run Code Online (Sandbox Code Playgroud)
我按如下方式在组件中导入CSS
About/index.js
import './style.css';
export default class About extends Component {
render() {
# Return some component
}
}
Run Code Online (Sandbox Code Playgroud)
但是,CSS将在该<header>部分中导入并保持全局范围.
我期待CSS是:
但是,在从浏览器进行检查时,会在该<header>部分指定样式并将其应用于所有组件
<header>
// Stuff
<style type="text/css">style for component About</style>
<style type="text/css">style for component B</style>
<style type="text/css">style for component C</style>
// Stuff
</header>
Run Code Online (Sandbox Code Playgroud)
如何将CSS导入为组件范围?好像我正在理解React ES6中的CSS导入错误.
我正在学习本教程
编辑
Brett的回答是正确的.但是,我的问题变成了其他地方.我使用create-react-app创建了我的应用程序,它基本上简化了做React所需的设置.它包括WebPack,Babel和其他要开始的事情.它使用的默认WebPack配置没有设置模块选项,css-loader因此它默认为false,因此未启用本地范围.
仅仅是为了获得更多信息,似乎create-react-app没有直接的方式来定制WebPack配置,但似乎有很多如何在Web上进行解决方法.
Bre*_*ody 25
这听起来像CSS模块做你想要的.
CSS模块是一个CSS文件,默认情况下,所有类名和动画名都在本地作用域.所有URL(url(...))和@imports都是模块请求格式(./xxx和../xxx表示相对,xxx和xxx/yyy表示在modules文件夹中,即在node_modules中).
这是一个简单的例子:
假设我们有一个React组件,如:
import React from 'react';
import styles from './styles/button.css';
class Button extends React.Component {
render() {
return (
<button className={styles.button}>
Click Me
</button>
);
}
}
export default Button;
Run Code Online (Sandbox Code Playgroud)
和一些CSS ./styles/button.css:
.button {
border-radius: 3px;
background-color: green;
color: white;
}
Run Code Online (Sandbox Code Playgroud)
在CSS模块执行它之后,生成的CSS将是:
.button_3GjDE {
border-radius: 3px;
background-color: green;
color: white;
}
Run Code Online (Sandbox Code Playgroud)
其中_3DjDE是随机生成的哈希 - 为CSS类提供唯一的名称.
替代
一个简单的替代方法是避免使用通用选择器(如p,code等),并采用了组件和元件基于类的命名约定.即使是像BEM这样的公约也有助于防止你遇到的冲突.
将此应用于您的示例,您可以使用:
.aboutContainer {
# Some style
}
.aboutContainer__code {
# Some style
}
Run Code Online (Sandbox Code Playgroud)
基本上,您需要设置样式的所有元素都将获得唯一的类名.
小智 9
您可以使用 SASS (.scss) 来模仿作用域 CSS。
假设您只需要在一个组件中使用引导程序(以避免冲突)。将组件包裹起来<div className='use-bootstrap'>,然后创建一个 .scss 文件,如下所示:
.use-bootstrap {
// Paste bootstrap.min.css here
}
Run Code Online (Sandbox Code Playgroud)
使用此文件命名约定[name].module.css
并查看文档:https://create-react-app.dev/docs/adding-a-sass-stylesheet
JSX 文件
import React from 'react';
import styles from './MyPage.module.scss';
const MyPage = () => {
return (
<div className={styles.myDiv}>
My Page
</div>
);
};
export default MyPage;
Run Code Online (Sandbox Code Playgroud)
样式文件
.myDiv {
color: #f3f3f3;
font-family: "Cambria";
font-weight: normal;
font-size: 2rem;
}
Run Code Online (Sandbox Code Playgroud)
因为您提到您使用了create-react-app,所以这里的解决方案很容易更改style.css为style.module.css,它看起来像这样:
import styles from "./style.css"
<button className={styles.button}>blabla</button>
Run Code Online (Sandbox Code Playgroud)
关于本文的更多信息:https : //blog.bitsrc.io/how-to-use-sass-and-css-modules-with-create-react-app-83fa8b805e5e
| 归档时间: |
|
| 查看次数: |
19009 次 |
| 最近记录: |