【发布时间】:2021-09-06 09:04:28
【问题描述】:
我有一个巨大的 react 应用程序,它有 4 个主要的大型 CSS(darkLTR、lightLTR、darkRTL、lightRTL),我知道这并不理想,但这是我老板为我买的网站模板并让我使用它(我想使用 Material ui,它非常适合主题处理,但遗憾的是我不被允许)。它带有两个不同的模板。暗模式和亮模式。他们告诉我,他们希望同时拥有深色和浅色模式,甚至 RTL 支持。所以我不得不将 ltr 翻译成 rtl 并添加切换按钮以在不同的主题和语言之间切换。我做了所有这些,现在我有所有样式的 4 个 CSS 文件。它们都有相同的类名和规则。唯一不同的是方向和颜色。我像下面这样导入这些 CSS 文件:
export default function importStylesheets() {
const theme = localStorage.getItem('theme')
const direction = localStorage.getItem('direction')
if (theme === 'dark' && direction === 'rtl') {
import('./css/styleDarkrtl.css')
} else if (theme === 'dark' && direction === 'ltr') {
import('./css/styleDarkltr.css')
} else if (theme === 'light' && direction === 'rtl') {
import('./css/styleLightrtl.css')
} else if (theme === 'light' && direction === 'ltr') {
import('./css/styleLightltr.css')
}
}
现在我的问题开始了。想象一下,我们处于 darkltr 模式,并且 darkltr CSS 已经加载。现在用户切换主题切换按钮。所以importStylesheets()函数会被再次调用,这一次主题的值会变轻。所以这次 lightltr 将被导入,整个主题将得到更新,一切看起来都很酷。但是如果用户再次切换主题切换按钮怎么办?什么都没发生。因为现在我调用importStylesheets() 函数,它不会重新导入darkltr CSS,因为它已经在应用程序缓存中。最后一个导入的文件(在本例中为 lightltr)具有更高的优先级。所以什么都不会改变。我想出了一个临时解决方案来重新加载整个应用程序并使用 localStorage 加载它,然后调用 importStylesheets() 函数。但这是一个巨大的劣势,因为我们使用 React 应用程序的原因之一是为了获得良好且快速的用户体验。所以我的问题是,有人可以帮我清除导入的内容吗?管他呢。我只需要能够随时在不同的 CSS 之间切换或将它们放在首位。请帮助我实现这个目标。非常感谢。
更新: 我在捆绑文件中找到了这部分代码。认为它可能会有所帮助
function importStylesheets() {
const theme = localStorage.getItem('theme');
const direction = localStorage.getItem('direction');
if (theme === 'dark' && direction === 'rtl') {
Promise.all(/*! import() */[__webpack_require__.e(0), __webpack_require__.e(1)]).then(__webpack_require__.t.bind(null, /*! ./css/styleDarkrtl.css */ "./src/css/styleDarkrtl.css", 7));
} else if (theme === 'dark' && direction === 'ltr') {
Promise.all(/*! import() */[__webpack_require__.e(0), __webpack_require__.e(3)]).then(__webpack_require__.t.bind(null, /*! ./css/styleDarkltr.css */ "./src/css/styleDarkltr.css", 7));
} else if (theme === 'light' && direction === 'rtl') {
Promise.all(/*! import() */[__webpack_require__.e(0), __webpack_require__.e(2)]).then(__webpack_require__.t.bind(null, /*! ./css/styleLightrtl.css */ "./src/css/styleLightrtl.css", 7));
} else if (theme === 'light' && direction === 'ltr') {
Promise.all(/*! import() */[__webpack_require__.e(0), __webpack_require__.e(4)]).then(__webpack_require__.t.bind(null, /*! ./css/styleLightltr.css */ "./src/css/styleLightltr.css", 7));
}
}
【问题讨论】:
-
你在使用 Create React App 吗?
-
是的,我正在使用 Create React App
标签: javascript css reactjs