簡體   English   中英

在一個組件中導入 CSS 正在將 CSS 影響添加到其他組件。 如何和為什么?

[英]Importing CSS in one component is adding CSS affect to other Components. How and Why?

我來自Angular Background ,據我所知。 Each component has its own beauty and till we import a CSS file inside it those CSS classes should not be applied even if we add to HTML Elements to the component in case we have not added or imported any CSS files for classes used inside this new/2nd component

我在React中所做的是 2 個組件 - Home1.jsHome2.js 當我將a css file named Home.css to Home1 Component不是Home2.js component時 - 世界上那些even too Home2 Component組件類如何影響應用。 這太荒謬了。

這就是為什么我要導入someFile.css **specifically** to the component where I want its affect to be there 這提供了一種encapsulation affect ,我看到它正在失敗。 現在,有人可以向我解釋一下,無論我在哪里不導入 someFile.css,這些課程也有影響嗎?

Home1.js

import React, { Component } from 'react';
import './home.css';

class Home1 extends Component {

  render() {
    return (
      <div>
          <div className="red">1...</div>
          <div className="green">2...</div>
          <button>click</button>
      </div>
    )

  }
}

export default Home1;

Home2.js

import React, {useState} from 'react';

const Home2 = () => {

  return (

    <div>
        <div className="red">1..</div>
        <div className="green">2...</div>
        <button>click</button>
    </div>
  )

}

export default Home2;

結果:

在此處輸入圖像描述

Angular 是通過viewEncapsulation來實現的,但是這個概念在 react 中並不存在。 您要么需要通過在組件的頂部節點上添加主 class 手動 scope css,要么使用可以為您執行此操作的庫(沒有嘗試過,您可以參考 @Abdel 的評論)。

在 React 中,就像有人已經評論過的那樣,您需要CSS 模塊來處理您的問題。 實際上,它已經包含在css-loader中,這是一個非常基本的模塊,您需要webpack在捆綁過程中處理 CSS 文件。 我不確定你是否從頭開始構建你的 React 應用程序,但我很確定你的項目中已經有了這個模塊。

{
  loader: 'css-loader',
    ...
  options: {           
  // Automatically enable css modules for files satisfying `/\.module\.\w+$/i` RegExp.
    modules: { auto: true },
  },
},

我相信你是一個經驗豐富的 web 應用程序程序員,只是抱怨 React 的設計,但我想在這里提供一點瀏覽器渲染機制的基本知識,為他們剛剛開始學習 web 編程和思考同樣的問題。

瀏覽器中渲染引擎的基礎是解釋 HTML、XML 文檔。 通過<script><style>等加載資產后。 有幾個步驟可以完成渲染 對像素應用 CSS 規則的步驟是樣式計算

What browser does is very simple, it takes the CSS files, applies the rules, something about the scope of the styles really rely on the practice of library/framework, you can imagine that the best they can do is preprocessing the CSS files and add每個 CSS 規則的一些獨特屬性對應於它可以在您的代碼中找到的特定 class 名稱。

在哪里導入 CSS 文件只是為了可讀性和可維護性。 In the old times, when people still program web app with jQuery or pure JS, you just include the CSS file in the .html file, maybe it forces you to care about the naming of the classes and styles earlier, but actually we also have當您嘗試將其分離用於更大的項目時,同樣的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM