Skip to content

Commit 9612cbc

Browse files
committed
fix: 使用 useReducer 强制更新修复主题切换
1 parent 31f7988 commit 9612cbc

1 file changed

Lines changed: 14 additions & 24 deletions

File tree

src/components/ThemeToggle.tsx

Lines changed: 14 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,22 @@
1-
import { useCallback, useSyncExternalStore } from 'react';
1+
import { useReducer } from 'react';
22

3-
function getIsDark() {
4-
return document.documentElement.classList.contains('dark');
5-
}
3+
export function ThemeToggle() {
4+
const [, forceUpdate] = useReducer((x: number) => x + 1, 0);
5+
const isDark = typeof document !== 'undefined' && document.documentElement.classList.contains('dark');
66

7-
function subscribe(callback: () => void) {
8-
const observer = new MutationObserver(callback);
9-
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
10-
return () => observer.disconnect();
11-
}
7+
const toggle = () => {
8+
const nowDark = document.documentElement.classList.contains('dark');
9+
const next = !nowDark;
1210

13-
function applyTheme(dark: boolean) {
14-
if (dark) {
15-
document.documentElement.classList.add('dark');
16-
} else {
17-
document.documentElement.classList.remove('dark');
18-
}
19-
localStorage.setItem('theme', dark ? 'dark' : 'light');
20-
const meta = document.querySelector('meta[name="theme-color"]');
21-
if (meta) meta.setAttribute('content', dark ? '#111110' : '#fafaf9');
22-
}
11+
document.documentElement.classList.toggle('dark', next);
12+
localStorage.setItem('theme', next ? 'dark' : 'light');
2313

24-
export function ThemeToggle() {
25-
const isDark = useSyncExternalStore(subscribe, getIsDark);
14+
const meta = document.querySelector('meta[name="theme-color"]');
15+
if (meta) meta.setAttribute('content', next ? '#111110' : '#fafaf9');
2616

27-
const toggle = useCallback(() => {
28-
applyTheme(!getIsDark());
29-
}, []);
17+
// Force re-render to update icon
18+
forceUpdate();
19+
};
3020

3121
return (
3222
<button

0 commit comments

Comments
 (0)