如何在ReactJS中删除导入的CSS [英] How to remove imported css in reactjs
问题描述
我已使用以下代码导入CSS
I have used the following code to import css
componentWillMount() {
import('./patient-summary.css');
}
不使用组件时如何从反应中删除导入的CSS.当我返回上一个屏幕时,此CSS将在此处应用.有什么主意吗?
How to remove imported css from react when component is not in use. When i go back to previous screen this css gets applied there. Any idea ?
更新:: Webpack配置
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'public/dist')
},
module: {
rules: [
{
test: /\.js?$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
loader: "file-loader"
}
,
{
test: /\.(png|jpeg|jpg|gif|svg)$/,
loader: "file-loader"
}
]
},
devServer: {
contentBase: path.resolve(__dirname, "public"),
historyApiFallback: true,
port: 3000,
watchOptions: {
// Delay the rebuild after the first change
aggregateTimeout: 300,
// Poll using interval (in ms, accepts boolean too)
poll: 1000,
},
},
plugins: [
// Ignore node_modules so CPU usage with poll
// watching drops significantly.
new webpack.WatchIgnorePlugin([
path.join(__dirname, "node_modules")
])
],
};
推荐答案
我在React中找到了一种(某种)合理的方法来做到这一点.简而言之,您可以包含导入"./style.css"
,然后在加载后即可捕获导入的样式表以切换其 StyleSheet.disabled 属性.
I found a (sort of) reasonable way to do this in React. In short, you can lazy-load React components that contain the import './style.css'
, and when it loads, you can capture the imported StyleSheet to toggle its StyleSheet.disabled property later.
这是主要代码,下面有更多解释.这是我的要点.
Here's the main code, with more explanation below. Here's my Gist.
import { useEffect } from 'react'
// global list of all the StyleSheets that are touched in useDisableImportedStyles
const switchableGlobalStyleSheets: StyleSheet[] = []
// just to clarify what createUseDisableImportedStyles() returns
type useDisableImportedStyles = () => void
export const createUseDisableImportedStyles = (
immediatelyUnloadStyle: boolean = true
// if true: immediately unloads the StyleSheet when the component is unmounted
// if false: waits to unloads the StyleSheet until another instance of useDisableImportedStyles is called.This avoids a flash of unstyled content
): useDisableImportedStyles => {
let localStyleSheet: StyleSheet
return () => {
useEffect(() => {
// if there are no stylesheets, you did something wrong...
if (document.styleSheets.length < 1) return
// set the localStyleSheet if this is the first time this instance of this useEffect is called
if (localStyleSheet == null) {
localStyleSheet = document.styleSheets[document.styleSheets.length - 1]
switchableGlobalStyleSheets.push(localStyleSheet)
}
// if we are switching StyleSheets, disable all switchableGlobalStyleSheets
if (!immediatelyUnloadStyle) {
switchableGlobalStyleSheets.forEach(styleSheet => styleSheet.disabled = true)
}
// enable our StyleSheet!
localStyleSheet.disabled = false
// if we are NOT switching StyleSheets, disable this StyleSheet when the component is unmounted
if (immediatelyUnloadStyle) return () => {
if (localStyleSheet != null) localStyleSheet.disabled = true
}
})
}
}
警告:这很挑剔.您必须完全进行设置,否则可能会导致意想不到的后果
WARNING: This is pretty finicky. You must set this up exactly or there may be unintended consequences
-
createUseDisableImportedStyles
必须在与导入的目标CSS和要延迟加载的组件相同的tsx文件的全局tsx文件中调用
createUseDisableImportedStyles
must called in global scope in the same tsx file as the imported css being targeted and the component to be lazy loaded
import React from 'react'
import { createUseDisableImportedStyles } from './useDisableImportedStyles'
import './global-styles.css'
const useDisableImportedStyles = createUseDisableImportedStyles()
export const CssComponent: React.FC<{}> = () => {
useDisableImportedStyles()
return null
}
export default CssComponent
- 使用该钩子的组件应该延迟加载:
LazyCssComponent = React.lazy(() => import('./cssComponent'))
...
<React.Suspense fallback={<></>}>
{condition && <LazyCssComponent/>}
</React.Suspense>
- 延迟加载的例外情况可能是在单个正常的非延迟组件中使用它,因此样式会在第一个渲染器上加载
- 注意:
InitialCssComponent
不需要实际渲染,只需要导入 - 但是:仅在全局导入一个 .css文件时,此方法才起作用,否则,我不知道会发生什么情况
- NOTE: the
InitialCssComponent
never needs to actually render, it just needs to be imported - BUT: this will only work if there is one single .css file imported globally, otherwise, I don't know what would happen
import InitialCssComponent from './initialCssComponent'
LazyCssComponent = React.lazy(() => import('./cssComponent'))
//...
{false && <InitialCssComponent/>}
<React.Suspense fallback={<></>}>
{condition && <LazyCssComponent/>}
</React.Suspense>
祝你好运!
这篇关于如何在ReactJS中删除导入的CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!