简体   繁体   中英

Isolate less styles to react component

I am trying to figure out how to get my react components to not pick up the css classes of another react component. So say I have a component called Home and one called About, and on the inside they both just contain a div with a className of header-container and their less imports like so:

Home:

import React, { Component } from 'react';

import './home.less';

class Home extends Component {
    render() {
        return (
            <div className='header-container'>
                <h1>Home</h1>
            </div>
        );
    }
}

export default Home;

About:

import React, { Component } from 'react';

import './about.less';

class About extends Component {
    render() {
        return (
            <div className='header-container'>
                <h1>About</h1>
            </div>
        );
    }
}

export default About;

And the less file for each looks like so with different colors (For this example lets say this is the about.less file):

.header-container {
    color: red;
}

Now when I use the react-router-dom and try to navigate to the home page, I am seeing the word Home but with the red color that is in the about less file, instead of the blue in my home.less file.

This is how I am navigating to the components

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom';

import Home from './home/home';
import About from './about/about';

class App extends Component {
    render() {
        return (
            <Router>
                <Switch>
                    <Route exact path='/' component={Home}/>
                    <Route path='/about' component={About}/>
                </Switch>
            </Router>
        );
    }
}

export default App;

Anybody have any suggestions on how I can seperate these to not affect eachother? Not sure if it helps, but when I am seeing this I am running webpack-dev-server to serve the files.

Edit: Also I noticed when I inspect element on the page loaded, I am seeing the following css in my head element.

在此处输入图片说明

If it's going to be in the same app and you want to use an external style sheet, it's recommended that you name the two div s differently.

eg <div className='about-page__header-container'> <div className='home-page__header-container'>

This is because the css styles imported as the style sheet are global.

An alternative would be to use inline style, which is becoming increasingly popular in React.js community.

For a comparison of the two options, see The Debate Around "Do We Even Need CSS Anymore?"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM