Skip to content

Commit b5aa81b

Browse files
authored
Merge pull request #232 from hmydgz/dev
✨ feat(ThemeSwitchButton): 新增在未手动设置主题时跟随系统主题的功能
2 parents c4386d7 + 67fb8a6 commit b5aa81b

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

src/components/ThemeSwitchButton.tsx

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import { Button } from '@blueprintjs/core'
22

33
import { useEffect, useState } from 'react'
44

5+
const themeMedia = window.matchMedia('(prefers-color-scheme: light)')
6+
57
export const ThemeSwitchButton = () => {
68
const [theme, setTheme] = useState(localStorage.getItem('theme') || '')
79
const handleThemeSwitch = () => {
@@ -10,7 +12,11 @@ export const ThemeSwitchButton = () => {
1012
localStorage.setItem('theme', isCurrentDark ? 'light' : 'dark')
1113
}
1214
useEffect(() => {
13-
if (theme == 'dark') {
15+
if (!themeMedia.matches && !localStorage.getItem('theme')) {
16+
handleThemeSwitch()
17+
return
18+
}
19+
if (theme === 'dark') {
1420
document.body.classList.add('bp4-dark')
1521
document.body.classList.add('dark')
1622
} else {
@@ -22,6 +28,6 @@ export const ThemeSwitchButton = () => {
2228
<Button
2329
onClick={handleThemeSwitch}
2430
icon={theme === 'dark' ? 'moon' : 'flash'}
25-
></Button>
31+
/>
2632
)
2733
}

0 commit comments

Comments
 (0)