React:仅在呈现组件时加载组件的 CSS

IT技术 reactjs react-router webpack-2 css-loader
2021-04-15 07:37:10
# 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'));

当我去/mycomponentMyComponent 渲染它的 css 时。但是当我转到任何其他 url 时,仍然可以在 html 的 Head 中看到 MyComponentStyle.css。有没有办法仅在组件在其路由上呈现时呈现相应的组件 CSS?

1个回答

的WebPack V2推出了一个叫做动态导入通过import()你可以将你的 CSS 导入移动到renderorcomponentWillMount方法中,由一个布尔变量保护以确保你只加载它一次。

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