javascript - 如何在 reactjs 中删除导入的 css

标签 javascript css reactjs import redux

我已经使用下面的代码导入css

componentWillMount() {
    import('./patient-summary.css');
}

如何在组件未使用时从 React 中删除导入的 css。当我返回到上一个屏幕时,此 CSS 会应用到那里。有什么想法吗?

更新::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 中找到了一种(某种程度上)合理的方式来做到这一点。总之,你可以lazy-load React components包含 import './style.css',当它加载时,您可以捕获导入的 StyleSheet切换其 StyleSheet.disabled以后的属性(property)。

这是主要代码,下面有更多解释。这是我的 Gist .

useDisableImportedStyles.tsx

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
            }

        })
    }
}

警告:这非常挑剔。您必须准确设置,否则可能会产生意想不到的后果

条件:

  1. createUseDisableImportedStyles 必须在与要定位的导入 css 和要延迟加载的组件相同的 tsx 文件中在全局范围内调用
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
  1. 使用这个钩子(Hook)的组件应该被延迟加载:
LazyCssComponent = React.lazy(() => import('./cssComponent'))
...
<React.Suspense fallback={<></>}>
    {condition && <LazyCssComponent/>}
</React.Suspense>
  1. 延迟加载的一个异常(exception)可能是在单个正常的非延迟组件中使用它,以便在第一次渲染时加载样式
  • 注意:InitialCssComponent 不需要实际渲染,只需要导入
  • 但是:这只有在全局导入一个 .css 文件时才有效,否则,我不知道会发生什么
import InitialCssComponent  from './initialCssComponent'
LazyCssComponent = React.lazy(() => import('./cssComponent'))
//...
{false && <InitialCssComponent/>}
<React.Suspense fallback={<></>}>
    {condition && <LazyCssComponent/>}
</React.Suspense>

祝你好运!

关于javascript - 如何在 reactjs 中删除导入的 css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48047362/

相关文章:

javascript - 尝试使用构造函数处理嵌套对象时出错

javascript - 在组件中加载多个脚本

javascript - Ext js 中的一切都是蓝色的吗?

javascript - React useState() bool 切换组件添加而不是替换值

javascript - Dnd-kit:在 Droppable 上拖动时事件项目会失去顺序

javascript - 使用javascript在谷歌地图中绘制多边形

javascript - 当我使用 window.close ajax 调用时不起作用?

javascript - 使用 jQuery 输出彼此相邻的同级 div

html - 无法使箭头尖端更长

reactjs - React Hooks - 作为 prop 传递的函数组件内的函数无法访问状态