【发布时间】:2021-07-11 10:53:10
【问题描述】:
所以我试图在我使用 Bootstrap 制作的网站中交替使用浅色和深色主题。一切都很好,但问题是浏览器在刷新网站后不会“记住”它所在的主题,即使它应该在组件被渲染时检索主题。
import React, {useState, useEffect} from 'react'
import Link from "next/link"
export default function Navbar() {
const localTheme = typeof window !== 'undefined' ? localStorage.getItem('theme') : true
const [theme, setTheme] = useState(localTheme);
useEffect(() => localStorage.setItem("theme", theme), [theme])
return (
<header>
<nav className={theme ? "navbar navbar-expand-lg bg-light navbar-light py-3" : "navbar navbar-expand-lg bg-dark navbar-dark py-3"}>
<--Rest of Navbar--!>
<div className="form-check form-switch ms-3">
<input onClick={() => setTheme(!theme)} className="form-check-input" type="checkbox" id="flexSwitchCheckDefault"/>
<label className="form-check-label fw-bold" htmlFor="flexSwitchCheckDefault" style={theme ? {color: "black"} : {color:"white"}}>{theme ? "Light" : "Dark"} Theme</label>
</div>
</div>
</div>
</nav>
</header>
【问题讨论】:
-
请添加更多详细信息。你能看到本地存储中的主题值吗?在 chorme devtools 中转到应用程序选项卡并检查那里。
-
@Itaywazana 我的错,应该添加一张图片。是的,它正确地检索了主题值。
标签: javascript reactjs twitter-bootstrap next.js