【发布时间】:2021-09-20 10:30:52
【问题描述】:
我希望能够在 primereact 中的主题之间切换,而不是导入一个主题,然后它会影响我的整个应用程序,我没有在暗模式或亮模式之间切换的选项。
【问题讨论】:
标签: reactjs primereact
我希望能够在 primereact 中的主题之间切换,而不是导入一个主题,然后它会影响我的整个应用程序,我没有在暗模式或亮模式之间切换的选项。
【问题讨论】:
标签: reactjs primereact
在www.primefaces.org/primereact/showcase/ 网站上观察他们是如何做到的,打开 Developer view: Elements,可以注意到选择不同的主题会改变 HTML 标头中的 css 文件链接:
<link id="theme-link" rel="stylesheet" href="./themes/bootstrap4-light-blue/theme.css">
变成
<link id="theme-link" rel="stylesheet" href="./themes/bootstrap4-light-purple/theme.css">
将链接元素 HREF 从一个切换到另一个是相当容易的。
本页讨论了 Primereact 主题切换: Switch Your React App Between Material, Bootstrap and Custom Themes at Runtime
但它描述的方法太复杂了,涉及弹出和自定义 webpack,捆绑所有主题 CSS 文件并以编程方式导入它们,就像这样:
const changeTheme = (theme) => {
import(`./${theme}.scss`).then((module) => {
if (selectedThemeModule) {
selectedThemeModule.unuse();
}
module.use();
setSelectedThemeModule(module);
});
}
取而代之的是,获取他们执行链接 HREF 交换方法的示例 repo:github.com/mertsincan/primereact-dynamic-theming/
example-1 有上面页面中的卷积方法的代码,你可以跳过它并转到 example-2,这要简单得多。
简而言之,在
<link id="app-theme" rel="stylesheet" type="text/css" href="saga-blue.css">
并使用此功能:
const changeTheme = (theme) => {
let themeLink = document.getElementById('app-theme');
if (themeLink) {
themeLink.href = theme + '.css';
}
}
然后在点击主题 XXX 时调用changeTheme(XXX)。
接下来将 .css 文件放到正确的位置 - 只需将所有 node_modules/primereact/themes/*/theme.css 文件复制到公共文件夹中(给它们相应的主题名称)。一些 theme.css 参考字体 - 在每个文件中搜索“url”,如果存在,也复制相应的 fonts/ 目录。
我应该提到 example-1 的好处是使用了缩小和捆绑的 CSS 文件,因此主题切换得更快。如果这很重要,请按照上面链接的教程和示例 1 进行操作。另请注意,example-2 与 example-1 具有非常相似的设置(弹出和自定义 webpack 配置),但仅将 css 文件复制到正确的输出文件夹,可以跳过该文件夹以支持手动复制文件一次。
【讨论】: