首页 > 解决方案 > 我如何不让 CSS 文件在 React 中继承?

问题描述

我目前正在尝试设置一个多页 React 项目,但是当我创建一个新页面时,它会应用每个 CSS 页面,而不仅仅是在*.js文档开头导入的那个。

例如,我有一个globalstyle.css文件应用到几乎每个页面上使用 import '../css/globalstyle.css'的每个页面。

但是,我有一页我不想打开它,但无论如何它都会应用cssglobalstyle.css我猜这是因为App.js一次加载每个页面,但我不知道如何解决这个问题。

class App extends Component { 


 render() {
    return (
  <React.Fragment>
    <HashRouter name="app" path="/" handler={App} basename={process.env.PUBLIC_URL}>

     <SideNav/>
     <TopBar/>

      <Switch>
        <Route path = "/pages/dashboard.js" exact component={Dashboard} />
        <Route path = "/pages/home.js" exact component={Home} />
        <Route path = "/pages/tips.js" exact component={Tips} />
      </Switch>
      <Redirect from="/" exact to="/pages/home.js" />

    </HashRouter>

  </React.Fragment>
    );
  }
} 

我不想要主页上的 globalstyle。

标签: cssreactjs

解决方案


我知道解决这个问题的唯一方法是使用 css 模块。引入 CSS 模块来解决这个问题。

如果您使用的是 create-react-app ,那么它是开箱即用的。参考这里 https://create-react-app.dev/docs/adding-a-css-modules-stylesheet/

如果您想在非 create-react-app 应用程序中进行设置,请参阅此处 https://programmingwithmosh.com/react/css-modules-react/

希望这有帮助。


推荐阅读