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

时间:2017-08-08 06:28:20

标签: reactjs react-router webpack-2 css-loader

# 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时。但是当我去任何其他网址时,MyComponentStyle.css仍然可以在html的头部看到。有没有办法只在组件在其路径上呈现时呈现相应的组件CSS?

1 个答案:

答案 0 :(得分:4)

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