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

React+TailwindCSS暗黑模式默认设置异常:切换按钮状态不匹配

问题:React+TailwindCSS暗黑模式默认设置异常

我在为网页实现React+TailwindCSS的暗黑模式切换功能,原教程运行正常,但将默认模式改为暗黑后出现问题:

  • 首次访问页面时,localStorage无对应值会返回undefined,我修改代码后页面能切换为暗黑模式,但切换按钮状态异常(应显示白色月亮图标,实际显示黑色太阳)
  • 查看React开发者工具发现状态未更新,高亮显示的状态应为true,实际为false
  • 当localStorage存在有效值后,功能恢复正常

问题截图
React DevTools状态截图

相关代码

useDarkMode.tsx

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

export default function useDarkMode() {
    const [theme, setTheme] = useState(localStorage.theme);
    if (typeof theme === 'undefined') {
        setTheme('dark');
    }
    const colourTheme = theme === 'dark' ? 'light' : ('light' ? 'dark' : 'light');

    useEffect(() => {
        const root = window.document.documentElement;
        root.classList.remove(colourTheme);
        root.classList.add(typeof theme === 'undefined' ? 'dark' : theme);

        localStorage.setItem('theme', typeof theme === 'undefined' ? 'dark' : theme);
    }, [theme, colourTheme]);

    return [colourTheme, setTheme] as any;
}
export default function Nav(props: any) {
    const [colourtheme, setTheme] = useDarkMode();
    const [isDarkMode, setDarkMode] = useState(
        colourtheme === "dark" ? true : false
    );
    
    const dmProps = {
        colourtheme: colourtheme,
        setTheme: setTheme,
        isDarkMode: isDarkMode,
        setDarkMode: setDarkMode,
    };

....

<Switcher className="flex flex-col ml-2 mr-1.5 md:flex-row md:space-x-8 md:mt-0" functions={dmProps} />

switcher.tsx

import React, { useState } from 'react';
import { DarkModeSwitch } from 'react-toggle-dark-mode';

export default function Switcher(props: any) {

    function toggleDarkMode(checked: boolean):void {
        props.functions.setTheme(props.functions.colourtheme);
        props.functions.setDarkMode(checked);
    }

    return (
        <div className={`flex flex-col items-center w-auto ${props.className}`}>
            <DarkModeSwitch
            style={{ }}
            checked={props.functions.isDarkMode}
            onChange={toggleDarkMode}
            size={25}
            />
        </div>
    );
};

内容的提问来源于stack exchange,提问作者Jack Pollock

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 12:48:29