reactjs 如何在React中添加暗类和本地存储

6l7fqoea  于 2023-01-08  发布在  React
关注(0)|答案(1)|浏览(112)
function Theme() {
  
  const toggleMode = (mode) => {
    if (mode === "add") {
      document.documentElement.classList.add("dark");
    } else {
      document.documentElement.classList.remove("dark");
    }
  };
  const mode = localStorage.getItem("mode");
  return (
    <div className="theme_toggle">
        <div className="day_mode flex items-center" onClick={() => toggleMode("add")} >
          <Image src="/dark.svg" width="20" height="20" alt="night_mood" />
        </div>
        <div className="night_mode flex items-center" onClick={() => toggleMode("remove")} >
          <Image src="/day_white.svg" width="20" height="20" alt="day_mood" />
        </div>
    </div>
  )
}

export default Theme

我试图添加黑暗类的HTML标记,但我想刷新后,它应该保存。

aamkag61

aamkag611#

只需保存并从localStorage获取它,然后将其应用于正在使用文档效果
例如:

function Theme() {

  useEffect(()=>{
    const mode = localStorage.getItem("mode");
  
  
     if(mode){
       document.documentElement.classList.add("dark");
    
     }

   },[])
  
  const toggleMode = (mode) => {
    if (mode === "add") {
      document.documentElement.classList.add("dark");
      localStorage.setItem('mode','dark')
    } else {
      document.documentElement.classList.remove("dark");
      localStorage.removeItem('mode')
      
    }
  };
  return (
    <div className="theme_toggle">
      <div className="day_mode flex items-center" onClick={() => toggleMode("add")} >
        <Image src="/dark.svg" width="20" height="20" alt="night_mood" />
      </div>
      <div className="night_mode flex items-center" onClick={() => toggleMode("remove")} >
        <Image src="/day_white.svg" width="20" height="20" alt="day_mood" />
      </div>
    </div>
  )
}

export default Theme

相关问题