如何在 React 应用程序中设置系统首选项黑暗模式,同时允许用户来回切换当前主题

Coz*_*ozy 6 javascript css reactjs react-context react-hooks

我有一个反应网络应用程序,在导航上有一个主题切换。我有一个ThemeProvider Context具有自动检测用户的系统主题首选项并设置它的逻辑。然而,我认为用户应该能够在网站上来回切换主题,无论他们的系统偏好如何。这是ThemeContext.js包含所有主题逻辑(包括方法)的文件toggle

import React, { useState, useLayoutEffect } from 'react';

const ThemeContext = React.createContext({
    dark: false,
    toggle: () => {},
});

export default ThemeContext;

export function ThemeProvider({ children }) {
    // keeps state of the current theme
    const [dark, setDark] = useState(false);

    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)')
        .matches;
    const prefersLight = window.matchMedia('(prefers-color-scheme: light)')
        .matches;
    const prefersNotSet = window.matchMedia(
        '(prefers-color-scheme: no-preference)'
    ).matches;

    // paints the app before it renders elements
    useLayoutEffect(() => {
        // Media Hook to check what theme user prefers
        if (prefersDark) {
            setDark(true);
        }

        if (prefersLight) {
            setDark(false);
        }

        if (prefersNotSet) {
            setDark(true);
        }

        applyTheme();

        // if state changes, repaints the app
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [dark]);

    // rewrites set of css variablels/colors
    const applyTheme = () => {
        let theme;
        if (dark) {
            theme = darkTheme;
        }
        if (!dark) {
            theme = lightTheme;
        }

        const root = document.getElementsByTagName('html')[0];
        root.style.cssText = theme.join(';');
    };

    const toggle = () => {
        console.log('Toggle Method Called');

        // A smooth transition on theme switch
        const body = document.getElementsByTagName('body')[0];
        body.style.cssText = 'transition: background .5s ease';

        setDark(!dark);
    };

    return (
        <ThemeContext.Provider
            value={{
                dark,
                toggle,
            }}>
            {children}
        </ThemeContext.Provider>
    );
}

// styles
const lightTheme = [
    '--bg-color: var(--color-white)',
    '--text-color-primary: var(--color-black)',
    '--text-color-secondary: var(--color-prussianBlue)',
    '--text-color-tertiary:var(--color-azureRadiance)',
    '--fill-switch: var(--color-prussianBlue)',
    '--fill-primary:var(--color-prussianBlue)',
];

const darkTheme = [
    '--bg-color: var(--color-mirage)',
    '--text-color-primary: var(--color-white)',
    '--text-color-secondary: var(--color-iron)',
    '--text-color-tertiary: var(--color-white)',
    '--fill-switch: var(--color-gold)',
    '--fill-primary:var(--color-white)',
];

Run Code Online (Sandbox Code Playgroud)

因此,当页面加载时,显示用户的系统首选它们,但也允许用户通过单击触发该toggle功能的切换按钮来切换主题。在我当前的代码中,当toggle调用时,状态更改似乎发生了两次,因此主题保持不变。如何确保该toggle方法正确运行?

这是有问题的网络应用程序

Thr*_*ovn 6

对于所有想要订阅系统范围配色方案更改的人:

我扩展了@Daniel Danielecki 的精彩答案:

useEffect(() => {
  const mq = window.matchMedia(
    "(prefers-color-scheme: dark)"
  );

  if (mq.matches) {
    setIsDark(true);
  }

  // This callback will fire if the perferred color scheme changes without a reload
  mq.addEventListener("change", (evt) => setIsDark(evt.matches));
}, []);
Run Code Online (Sandbox Code Playgroud)

通过向媒体查询添加事件监听器,您可以监听深色主题的变化。如果您的用户有基于当前时间的自适应暗/亮模式周期,这非常有用。


Bar*_*yle 1

问题是useLayoutEffect每次值发生变化时整个块都会运行dark。因此,当用户切换时darkprefers...if 语句将运行并setDark返回到系统首选项。

要解决此问题,您需要跟踪用户手动切换主题,然后阻止prefers...if 语句运行。

在您中ThemeProvider执行以下操作:

  • 添加一个状态来监控用户是否使用了切换
const [userPicked, setUserPicked] = useState(false);
Run Code Online (Sandbox Code Playgroud)
  • 更新您的toggle功能:
const toggle = () => {
  console.log('Toggle Method Called');

  const body = document.getElementsByTagName('body')[0];
  body.style.cssText = 'transition: background .5s ease';

  setUserPick(true) // Add this line
  setDark(!dark);
};
Run Code Online (Sandbox Code Playgroud)
  • 最后,更新useLayout为如下所示:
useLayoutEffect(() => {
  if (!userPicked) { // This will stop the system preferences from taking place if the user manually toggles the them
    if (prefersDark) {
      setDark(true);
    }

    if (prefersLight) {
      setDark(false);
    }

    if (prefersNotSet) {
      setDark(true);
    }
  }

  applyTheme();
}, [dark]);
Run Code Online (Sandbox Code Playgroud)

您的切换组件不必更改。

更新:

萨尔的回答是一个很好的选择。我的指出了现有代码中的缺陷以及如何添加它。这指出了如何使您的代码更有效。

export function ThemeProvider({ children }) {
  const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;

  const [dark, setDark] = useState(prefersDark);

  useLayoutEffect(() => {
    applyTheme();
  }, [dark]);

  ...

}
Run Code Online (Sandbox Code Playgroud)