使用Reaction路由器路由到另一个组件时,CSS不变 [英] CSS not changing when using React Router to route to another component

查看:21
本文介绍了使用Reaction路由器路由到另一个组件时,CSS不变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用react-router-dom将我的应用程序路由到另一个组件时,CSS不会更改。

这是演示代码的最低限度版本

App.js

import React from 'react';
import Home from './Home';

function App() {
    return (
      <div>
        <Home></Home>
      </div>
    );
}

export default App;

Home.js

import React from 'react';
import './Home.css';

const Home = () => {
    return (
        <h1>Home</h1>
    );
}

export default Home;

Home.css

body {
    background-color: blue;
}

Dashboard.js

导入来自‘REACT’的反应; 导入‘./Dashboard.css’;

import React from 'react';
import './Dashboard.css';

const Dashboard = () => {
    return (
        <div className='content'>
            <h1>Dashboard</h1>
        </div>
    );
}

export default Dashboard;

Dashboard.css

.content {
    display: flex;
    align-content: center;
    align-items: center;
}

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Dashboard from './Dashboard';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter as Router, Route } from 'react-router-dom';

ReactDOM.render(
    <Router>
        <div>
        <Route exact path='/' component={App} />
        <Route path='/dashboard' component={Dashboard} />
        </div>
    </Router>, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: ...
serviceWorker.unregister();

当我执行/dashboard时,它会加载Dashboard组件,但它会保留从驻留App组件的Home组件加载的前一个CSS。背景保持为蓝色。我希望当我路由到另一个组件时,因为我更改了URL,它会加载新组件附加到它的任何CSS,并删除以前的任何CSS。这可能吗?

编辑:我在CodeSandbox中做了一个例子来说明。由于操场的限制,它与上面的代码略有不同,但功能是相同的。

可以看到,作为模块导入最终会将其导入到全局。如果我们注释import Home from "./Home";行,蓝色背景将消失。只需导入组件,即可导入整个CSS,尽管以模块化方式导入了CSS。我不确定我是否遗漏了什么。

编辑2:

以下是我尝试过的不同解决方案:

  1. css模块,但仍全局加载了正文样式。

  2. 样式组件不允许我修改正文html选择器css。它们要求我创建<div>元素 然后让这个元素跨越整个身体,我会设计出来的 就像是身体一样。这是一个我不想使用的变通方法,因为为此,我宁愿对全身跨度使用css模块。

    /li>
  3. 内联样式也不允许我修改正文html选择器css。我还需要使用像样式组件中那样的主体跨越<div>这样的解决办法。

推荐答案

问题

当您像在这里一样导入一个CSS时

import './Home.css';

您是在全局范围内导入它,这意味着它在导入后不会消失。


解决方案

CSS模块

您需要的是CSS Modules,其用法如下:

import styles from './Home.css';

<a className={styles.myStyleClass}>Hello</a>

样式组件

或css-in-js框架,如styled components,其用法如下:

import styled from 'styled-components';

const MyStyledElement = styled.a`
    color: blue;
`;

<MyStyledElement>Hello</MyStyledElement>

常规对象/内联样式

或者只是像这样的"常规"css-in-js:

const myStyle = {
    color: blue;
}

<a style={myStyle}>Hello</a>

造型有很多选择,这些都是很受欢迎的选择,我鼓励你去探索,看看你喜欢哪一个。

这篇关于使用Reaction路由器路由到另一个组件时,CSS不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆