【问题标题】:React switch css in Routes在路由中反应切换 css
【发布时间】:2022-01-15 13:13:35
【问题描述】:

我正在尝试制作一个小的 React App,这是我第一次使用 Router。

import { render } from "react-dom";
import {
  BrowserRouter,
  Routes,
  Route
} from "react-router-dom";
import App from "./App";
import Shop from './routes/shop';
import style1 from "./App.css";
import style2 from "./shop.css";





const rootElement = document.getElementById("root");
render(
  <BrowserRouter>
    <div style={style1}><Routes>
        <Route path="/" element={<App/>} />
    </Routes></div>
    <div style={style2}><Routes>
        <Route path="shop" element={<Shop />}/>
    </Routes></div>
  </BrowserRouter>,
  rootElement
);

效果很好,我可以使用 http://localhost:3000/ 和 http://localhost:3000/shop,但它不会切换 css 文件。

both CSS files get loaded on both pages

我知道 React 是一个单页应用程序,但请告诉我如何从 http://localhost:3000/shop 中删除 frickin App.css

所以我想要 http://localhost:3000/ 上的 App.css 和 http://localhost:3000/shop 上的 Shop.css

我会非常感谢每一个答案!

【问题讨论】:

    标签: javascript html css reactjs


    【解决方案1】:

    补充一下 Shivam 所说的,你的代码目前正在发生的事情是 React 正在导入两个 CSS 文件并应用它们。

    这是因为您使用的语法不正确。您不能将 css 文件作为其他内容导入: import styles1 from "./App.css" 其实就是导入 App.css 并应用到 App.js 和 Shop.js 上。

    你可以按照 Shivam 所说的去做,但是,如果你想按照你想要的方式来设计你的 react 应用程序,你可以使用css modules

    这些以您尝试使用 css 文件的方式工作 - 您可以导入它们并使用内联样式。但是,我不推荐这种方法,因为您必须以这种方式为“App.js”中的每个 JSX 表达式设置样式。仅设置 'style={style}' 只会将带有该样式组件的道具传递给 App.js,它实际上并没有应用它。

    看看这个link。它涵盖了 css 模块和一些其他在 react 中设置 css 样式的方法。最好的!

    【讨论】:

      【解决方案2】:

      我不明白你为什么在浏览路由时要声明 CSS 样式。
      只需在您的 component.js 中导入您的 CSS 文件
      就像在你的情况下,

      import { render } from "react-dom";
      import {
        BrowserRouter,
        Routes,
        Route
      } from "react-router-dom";
      import App from "./App";
      import Shop from './routes/shop';
      
      const rootElement = document.getElementById("root");
      render(
        <BrowserRouter>
          <Routes>
              <Route path="/" element={<App/>} />
          </Routes>
          <Routes>
              <Route path="shop" element={<Shop />}/>
          </Routes>
        </BrowserRouter>,
        rootElement
      );
      

      这是你的组件,

      import "./App.css";
      import React from 'react';
      
      export default function App(){
       //YOUR CODE HERE
      }
      

      另一个商店组件

      import "./shop.css";
      import React from 'react';
      
      export default function Shop(){
       //YOUR CODE HERE
      }
      

      这会很好用!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-18
        • 2021-06-18
        • 2019-08-03
        • 2018-06-02
        • 2021-01-09
        • 2020-08-22
        • 2019-01-28
        • 1970-01-01
        相关资源
        最近更新 更多