Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

reactjs - React: Load component's CSS only when component is rendered

# MyComponent.js

import React from 'react'
import './MyComponentStyle.css'

export default class MyComponent extends React.Component {
   ....
}


# App.js

import React from 'react'
import ReactDOM from 'react-dom'
import { Route, Switch, BrowserRouter } from 'react-router-dom'
import MyComponent from './MyComponent'
import PageNotFound from './PageNotFound'

ReactDOM.render(
  <BrowserRouter>
    <Switch>
        <Route exact path='/mycomponent' component={MyComponent}/>
        <Route component={PageNotFound} />
      </Switch>
  </BrowserRouter>,
  document.getElementById('root'));

When i go to /mycomponent MyComponent renders with its css. But when i go to any other url, MyComponentStyle.css still can be seen in html's Head. Is there way to render respective components CSS only when component is rendered on its route?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Webpack v2 introduced a feature called dynamic import via import(). You could move your CSS import into the render or componentWillMount methods, guarded by a boolean variable to ensure you only load it once.

import React from 'react'

let cssLoaded = false;

export default class MyComponent extends React.Component {
    render() {
        if (cssLoaded === false) {
            cssLoaded = true;
            import('./MyComponentStyle.css');
        }

        // other stuff
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...