【问题标题】:How do I prevent the css in one component from affecting the css in another component in React?如何防止一个组件中的 css 影响 React 中另一个组件中的 css?
【发布时间】:2022-01-27 15:54:13
【问题描述】:

我是 React 新手,所以我不确定为什么会发生这种情况。使用 React Router,我有三个路由,//signup/login,并且每个组件中的 css 导入溢出到其他组件的 css 中,破坏了样式。在这种情况下,而不是 div 元素 word 是每个组件的 css 中描述的颜色,它们都显示为绿色,这应该只发生在 Signup 组件中。我该怎么做才能解决这个问题?

App.js

import HomePage from './pages/HomePage/HomePage'
import LoginPage from './pages/LoginPage/LoginPage'
import SignupPage from './pages/SignupPage/SignupPage'
import  {BrowserRouter as Router, Switch, Route} from 'react-router-dom'

function App() {
    return (
      <Router>
        <Switch>
          <Route path="/" exact component={HomePage}/> 
          <Route path="/signup" component={SignupPage}/>
          <Route path="/login" component={HomePage}/>
        </Switch>
      </Router>
    )
}

export default App;

LoginPage.js

import { React } from 'react'
import "./LoginPage.css"

export default function LoginPage(){
    return(
      //In css file, word is red, but comes out green instead
      <div className="word">login</div>
    )
}

SignupPage.js

import { React } from 'react'
import "./SignupPage.css"

export default function SignupPage(){
    return(
      //In css file, word is green
      <div className="word">signup</div>
    )
}

主页.js

import React, { useState } from 'react'
import "./HomePage.css"

export default function HomePage() {

    return (
         //In css file, word is hotpink, but comes out green instead
         <div className="word">Home</div>
    )

有什么我需要添加到我的 App.js 文件中的吗?

【问题讨论】:

  • 尚不清楚根本问题是什么。为什么样式如此不同会产生问题?具体是什么问题?
  • 我会尽量描述性强,描述我的问题比我想象的要难一些。我遇到的问题是,在每条路线上,每个组件的 css 都会溢出到其他组件中。例如,简单地将元素 &lt;div className="word"&gt;example&lt;/div&gt; 添加到每个组件并在 css 文件中将其颜色分别更改为红色、蓝色和黄色,导致 example 在每个路由中为绿色。这说明了什么?
  • 我认为分享您的 CSS 定义将有助于理解问题
  • @DarienMiller 有几种方法可以解决这个问题,例如 CSS 模块、样式化组件或拥有每个组件唯一的父类。

标签: reactjs react-router


【解决方案1】:

为每个页面创建一个顶部 div:

export default function HomePage() {
return (
     <div className="homepage"><div className="word">Home</div></div>
)

对注册页面执行类似操作。

然后在css中

主页.css

 .homepage .word{
     
      color:red;
    
  }

signup.css

.signup .word{
 
  color:green;

 }

现在取决于您是在signup 页面内使用word 类还是homepage(任何级别的深度),word 将具有不同的样式。

【讨论】:

  • 这个解决方案实际上对我来说很完美,但是来自 html + css + raw Javascript,我很好奇为什么我需要将代码包装在一个更大的父 div 中以便 css在每个组件中不要与其他组件混合。
  • @DarienMiller react 不会根据组件 AFAIK 确定 css 的范围。
  • 啊,明白了!有道理,谢谢回答。
【解决方案2】:

防止这种情况的最佳方法是使用 CSS 模块,因为 CSS 模块让您可以在不同的文件中使用相同的 CSS 类名,而不必担心命名冲突

使用 CSS 模块很简单,只需遵循它的命名约定,如下所示,[name].module.css

示例:以下 CSS 模块的 CSS className 选择器是独立的

App.module.css

.container{
  color: #fff;
}

Navigation.module.css

.container{
  color: #000;
}

Click here to read more about CSS modules

【讨论】:

    猜你喜欢
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 2017-12-09
    • 2015-01-30
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    相关资源
    最近更新 更多