gpt4 book ai didi

reactjs - react : Load component's CSS only when component is rendered

转载 作者:行者123 更新时间:2023-12-03 13:36:39 25 4
gpt4 key购买 nike

# 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 的 Head 中看到。有没有办法仅当组件在其路由上渲染时渲染相应的组件CSS?

最佳答案

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

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

关于reactjs - react : Load component's CSS only when component is rendered,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45560806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com