reactjs - 如何在 primereact 中拥有主题切换器

我希望能够在 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,这样就简单多了。

简而言之,添加到“public/index.html”的 <header> 部分:

<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 文件复制到 public 文件夹中(给它们相应的主题名称)。一些 theme.css 引用字体 - 在每个文件中搜索“url”,如果存在,也复制相应的字体/目录。

我应该提到示例 1 的好处是使用缩小和捆绑的 CSS 文件,因此主题切换速度更快。如果这很重要,请按照上面链接的教程和示例 1 进行操作。另请注意,example-2 与 example-1 的设置非常相似(弹出和自定义 webpack 配置),但只是将 css 文件复制到正确的输出文件夹,可以跳过该步骤以支持手动复制文件一次。

https://stackoverflow.com/questions/68327342/

相关文章:

c - 为什么 GTK 4 报告 "assertion ' GTK_IS_WIDGET(部件 )'

javascript - 如何减少 GridStack 网格元素的最小高度和重量?

python - 我的损失函数在训练期间没有得到更小的值

sass - Stylelint 禁用规则, "no-descending-specificity"

python - 多次拟合时 keras fit() 的历史

javascript - A 帧动画框在特定区域随机移动

sql - 如何获得日期 + 时间的确定性计算值

rust - 如何正确处理 Warp 路由的错误

azure-devops - Azure Devops 管道 NPM 审计

schema - Protocol Buffer 架构无效。导入 "google/protobuf/