You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

主题切换时页面颜色未更新问题求助(附完整代码)

主题切换功能样式不更新问题排查

问题情况

开发主题切换功能,点击「Change Theme」按钮后,localStorage中的主题值已变化,但页面背景、文本及按钮颜色未同步切换,涉及三个文件:index.jsx、useLocalStorage.js和style.css。

代码片段

index.jsx

import useLocalStorage from "./useLocalStorage";

export default function DarkWhiteTheme() {
  const [theme, setTheme] = useLocalStorage("theme", "dark");

  const handleToggleTheme = () => {
    setTheme(theme === "light" ? "dark" : "light");
  };

  console.log(theme);

  return (
    <div className="light-dark-mode" data-theme={theme}>
      <div className="container">
        <h1>Hello World</h1>
        <button onClick={handleToggleTheme} className="change-theme-button">
          Change Theme
        </button>
      </div>
    </div>
  );
}

useLocalStorage.js

export default function useLocalStorage(key, defaultValue) {
  const [value, setValue] = useState(() => {
    let currentValue;
    try {
      currentValue = JSON.parse(
        localStorage.getItem(key) || String(defaultValue)
      );
    } catch (error) {
      console.log(error);
      currentValue = defaultValue;
    }

    return currentValue;
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
}

style.css

:root {
    --background : #ffffff
    --text-primary : #000000
    --button-bg: #000000
    --button-text: #ffffff
}

[data-theme='dark'] {
    --background: #000000
    --text-primary: #ffffff
    --button-bg: #ffffff
    --button-text: #000000
}

.light-dark-mode {
    background-color: var(--background);
    height: 100vh;
    display: flex;
    flex-direction: column;
    justify-content: center;
    font-size: 20px;
    transition: all 0.5s;
}

.light-dark-mode .container {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    gap: 30px;
}

.light-dark-mode .container p{
    color: var(--text-primary);
    font-size: 40px;
    margin: 0px;
}

.light-dark-mode .container button{
    background-color: var(--button-bg);
    border: 1px solid var(--button-bg);
    color: var(--button-text);
    padding: 12px;
    border-radius: 8px;
    font-weight: 600;
    cursor: pointer;
}

.change-theme-button{
    cursor: pointer;
}

问题原因及修复方案

1. CSS变量定义缺少分号(核心问题)

style.css中:root和[data-theme='dark']里的CSS变量都未添加分号,导致浏览器无法正确解析变量,样式无法随主题切换更新。

修复后CSS变量部分:

:root {
    --background : #ffffff;
    --text-primary : #000000;
    --button-bg: #000000;
    --button-text: #ffffff;
}

[data-theme='dark'] {
    --background: #000000;
    --text-primary: #ffffff;
    --button-bg: #ffffff;
    --button-text: #000000;
}

2. useLocalStorage钩子未导入React核心钩子

useLocalStorage.js中使用了useState和useEffect但未导入,会导致状态更新逻辑异常,即使localStorage有变化,组件状态可能无法正确触发重渲染。

修复后useLocalStorage.js:

import { useState, useEffect } from 'react';

export default function useLocalStorage(key, defaultValue) {
  const [value, setValue] = useState(() => {
    let currentValue;
    try {
      currentValue = JSON.parse(
        localStorage.getItem(key) || String(defaultValue)
      );
    } catch (error) {
      console.log(error);
      currentValue = defaultValue;
    }

    return currentValue;
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
}

3. 标题文本未绑定主题颜色

index.jsx中的<h1>标签未设置颜色样式,即使主题切换,标题颜色也不会变化,需添加对应样式。

修复后style.css中添加:

.light-dark-mode .container h1{
    color: var(--text-primary);
    font-size: 40px;
    margin: 0px;
}

完成以上修复后,点击按钮即可正常切换主题样式。

内容的提问来源于stack exchange,提问作者Abdul Basit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 17:47:31