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

我的未来我决定 提交于 2019-12-10 16:16:54

问题


# 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?


回答1:


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
    }
}


来源:https://stackoverflow.com/questions/45560806/react-load-components-css-only-when-component-is-rendered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!