代码之家  ›  专栏  ›  技术社区  ›  J. Hesters

MUI:使用类的深色模式

  •  0
  • J. Hesters  · 技术社区  · 4 年前

    我们正在建造下一个。js应用程序。我们正在从 pure Emotion MUI

    我们的应用程序有一个深色模式,可以通过将类分离并附加到文档来切换。我们不能使用React state,因为这会导致下一步中服务器端呈现代码的闪存。js。

    我们通过以下方式避免了那次闪光 noflash.js 脚本:

    (function () {
      // Change these if you use something different in your hook.
      var storageKey = 'darkMode';
      var classNameDark = 'dark-mode';
      var classNameLight = 'light-mode';
    
      function setClassOnDocumentBody(darkMode) {
        document.body.classList.add(darkMode ? classNameDark : classNameLight);
        document.body.classList.remove(darkMode ? classNameLight : classNameDark);
      }
    
      var preferDarkQuery = '(prefers-color-scheme: dark)';
      var mql = window.matchMedia(preferDarkQuery);
      var supportsColorSchemeQuery = mql.media === preferDarkQuery;
      // eslint-disable-next-line unicorn/no-null
      var localStorageTheme = null;
      try {
        localStorageTheme = localStorage.getItem(storageKey);
      } catch {
        // Do nothing
      }
      
      var localStorageExists = localStorageTheme !== null;
      if (localStorageExists) {
        localStorageTheme = JSON.parse(localStorageTheme);
      }
    
      // Determine the source of truth
      if (localStorageExists) {
        // source of truth from localStorage
        setClassOnDocumentBody(localStorageTheme);
      } else if (supportsColorSchemeQuery) {
        // source of truth from system
        setClassOnDocumentBody(mql.matches);
        localStorage.setItem(storageKey, mql.matches);
      } else {
        // source of truth from document.body
        var isDarkMode = document.body.classList.contains(classNameDark);
        localStorage.setItem(storageKey, JSON.stringify(isDarkMode));
      }
    })();
    

    The MUI docs

    有没有办法使用类设置MUI的值?(或由类设置的CSS变量?)

    Looks impossible now.

    0 回复  |  直到 4 年前
    推荐文章