css - 如何使 React CSS 导入组件范围?

标签 css reactjs

我有几个具有以下 CSS/组件结构的组件

About/style.css

.AboutContainer {
    # Some style
}

p > code {
    # Some style
}

然后我按如下方式在组件中导入CSS

About/index.js

import './style.css';

export default class About extends Component {
    render() {
         # Return some component
    }
}

但是,CSS 是在 <header> 中导入的部分并保持全局范围。

我期望 CSS 是:

  1. 组件范围内的样式仅适用于在此组件内呈现的内容。
  2. 如果组件被卸载,该组件的样式将消失。

但是,当从浏览器检查时,样式在 <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>

如何将 CSS 导入到组件范围内?看来我对 React ES6 中的 CSS 导入理解不正确。

我正在关注 this tutorial


编辑

Brett 的回答是正确的。但是,我的问题原来是在别的地方。我使用 create-react-app 创建了我的应用程序这基本上简化了执行 React 所需的设置。它包括 WebPack、Babel 和其他入门工具。它使用的默认 WebPack 配置没有设置 module option对于 css-loader所以它默认为 false ,因此未启用本地范围。

仅作为附加信息,似乎 create-react-app 没有直接的方法来自定义 WebPack 配置,但网络上似乎有许多解决方法。

最佳答案

听起来像CSS Modules ,或许多其他 CSS-in-JS 包,做你想做的。其他包括Emotion (我目前最喜欢的),Styled Components ,或许多包裹here .

A CSS Module is a CSS file in which all class names and animation names are scoped locally by default. All URLs (url(...)) and @imports are in module request format (./xxx and ../xxx means relative, xxx and xxx/yyy means in modules folder, i. e. in 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;

./styles/button.css 中的一些 CSS:

.button {
  border-radius: 3px;
  background-color: green;
  color: white;
}

在 CSS Modules 执行之后,生成的 CSS 将类似于:

.button_3GjDE {
  border-radius: 3px;
  background-color: green;
  color: white;
}

其中 _3DjDE 是一个随机生成的散列 - 为 CSS 类提供一个唯一的名称。

另一种选择

一个更简单的替代方案是避免使用通用选择器(如 pcode 等)并为组件和元素采用基于类的命名约定。甚至像 BEM 这样的约定将有助于防止您遇到的冲突。

将此应用于您的示例,您可能会:

.aboutContainer {
  # Some style
}

.aboutContainer__code {
  # Some style
}

基本上,您需要设置样式的所有元素都会收到一个唯一的类名。

关于css - 如何使 React CSS 导入组件范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47090574/

相关文章:

css - 我该如何解决这些布局问题?

javascript - Redux-form 字段数组,删除函数抛出奇怪的错误

javascript - anchor 标签在导航栏中不起作用

css - 页面布局中出现奇怪的空白。是什么原因造成的?

css - 在同一个 div 上使用 min-height % 和 px

javascript - React Js - 点击ant design stepper时如何更改URL?

reactjs - React Virtualized - 单击,展开行以获取更多详细信息

html - cake.generic.css : Can't decrease the width of a table inside a division 的 CSS 问题

javascript - 在react中有条件地导入引导文件

javascript - 向对象添加新属性