reactjs 如果激活了暗模式,则将复选框设置为选中或不选中|React

wdebmtf2  于 2022-11-04  发布在  React
关注(0)|答案(2)|浏览(101)

我是react的新手,我尝试了参考模式或状态模式,但是页面渲染了很多次,或者当我点击我的复选框时,不要改变选中的选项。
当我加载页面时,有一个条件检查是否激活了darkmode,因此如果loadind页面darkmode被启用,则复选框必须为true,如果没有,则必须为false,简单地

import React, {useEffect, useState} from "react";

function Header() {
    const [darkMode, setDarkMode] = useState(false);
    useEffect(() =>{
        if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
            document.documentElement.classList.add('dark')
            localStorage.theme = 'dark'
            setDarkMode(!darkMode)
          } else {
            document.documentElement.classList.remove('dark')
            localStorage.theme = 'light';
            console.log('modo luz activado')
          }
    },[])

  const changeTheme = () => {

    if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
      document.documentElement.classList.remove("dark");
      localStorage.theme = "light";
    } else {
      document.documentElement.classList.add("dark");
      localStorage.theme = "dark";
    }
  };

  return (
    <header>
      <nav>
        <input checked={darkMode} type="checkbox" onChange={changeTheme} />
      </nav>
    </header>
  );
}

export default Header;
5lhxktic

5lhxktic1#

您通常会使用React.useContext()来更改主题,但由于您是新手,因此我建议您采用以下方法来应对此挑战:

import React, {useEffect, useState} from "react";

function Header() {
    const [darkMode, setDarkMode] = useState( // initialize your state here directly
      localStorage.theme === 'dark' ||
      (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)
    );

    useEffect(() => { // move your logic part here
      if (!darkMode) {
        document.documentElement.classList.add('dark')
        localStorage.theme = 'dark'
      } else {
        document.documentElement.classList.remove('dark')
        localStorage.theme = 'light';
      }
    }, [darkMode])

  const changeTheme = () => {
    setDarkMode(!darkMode) // now just worry about changing your state
  };

  return (
    <header>
      <nav>
        <input checked={darkMode} type="checkbox" onChange={changeTheme} />
      </nav>
    </header>
  );
}

export default Header;

这样做的好处是你可以React性地处理你的主题逻辑。你可以观察你的状态的变化并实现你的逻辑,而不是每次都实现你的逻辑并改变你的状态。

zdwk9cvp

zdwk9cvp2#

change theme函数应该是这样的:

const changeTheme = () => {
    localStorage.theme = darkMode ? 'light' : 'dark'
    setDarkMode(!darkMode)
    if (darkMode) {
        document.documentElement.classList.remove("dark");
    } else {
        document.documentElement.classList.add("dark");
    }
};

相关问题