React:仅在渲染组件时加载组件的 CSS

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'));

当我转到 /mycomponent 时,MyComponent 使用其 css 进行渲染。但是当我去任何其他 url 时,MyComponentStyle.css 仍然可以在 html 的头像中看到。有没有办法只在组件在其路径上渲染时渲染各个组件 CSS?

Webpack v2 通过 import() 引入了一个名为 dynamic import 的功能。您可以将 CSS 导入移动到 rendercomponentWillMount 方法中,由布尔变量保护以确保您只加载一次。

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