加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何使React CSS导入组件作用域?

发布时间:2020-12-15 20:46:39 所属栏目:百科 来源:网络整理
导读:我有几个组件具有以下CSS /组件结构 关于/ style.css文件 .AboutContainer { # Some style}p code { # Some style} 我按如下方式在组件中导入CSS 关于/ index.js import './style.css';export default class About extends Component { render() { # Return
我有几个组件具有以下CSS /组件结构

关于/ style.css文件

.AboutContainer {
    # Some style
}

p > code {
    # Some style
}

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

关于/ index.js

import './style.css';

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

但是,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>

如何将CSS导入为组件范围?好像我正在理解React ES6中的CSS导入错误.

我跟随this tutorial

编辑

Brett的回答是正确的.但是,我的问题原来是在其他地方.我使用create-react-app创建了我的应用程序,它基本上简化了做React所需的设置.它包括WebPack,Babel和其他要开始的事情.它使用的默认WebPack配置没有为css-loader设置module option,因此默认为false,因此未启用本地范围.

仅仅是为了获得更多信息,似乎create-react-app没有直接的方式来自定义WebPack配置,但似乎有很多如何在Web上进行解决方法.

这听起来像 CSS Modules做你想要的.

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模块执行它之后,生成的CSS将是:

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

其中_3DjDE是随机生成的哈希 – 为CSS类提供唯一的名称.

替代

更简单的替代方法是避免使用泛型选择器(如p,代码等)并对组件和元素采用基于类的命名约定.即使像BEM这样的公约也有助于防止你遇到的冲突.

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

.aboutContainer {
  # Some style
}

.aboutContainer__code {
  # Some style
}

基本上,您需要设置样式的所有元素都将获得唯一的类名.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读