简体   繁体   English

如何在react中添加dark class刷新后保存

[英]how to add dark class add and save after refresh in react

how i can save dark class after refresh刷新后如何保存黑暗 class

import Image from 'next/image'
import React from 'react'

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

i am adding the cdark class to html tage but i want after refresh it will be save.我正在将 cdark class 添加到 html 标签,但我希望刷新后它会被保存。

simply save and get it from localStorage and apply it to document in useEffect简单地保存并从 localStorage 中获取它并将其应用于 useEffect 中的文档

sth like this:像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM