# 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 时,仍然可以在 html 的 Head 中看到 MyComponentStyle.css。有没有办法仅在组件在其路由上呈现时呈现相应的组件 CSS?