Skip to content

Commit

Permalink
update:使用上下文来处理夜间模式
Browse files Browse the repository at this point in the history
  • Loading branch information
nowscott committed Jul 21, 2024
1 parent c8e0b20 commit ca55f46
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 39 deletions.
24 changes: 18 additions & 6 deletions components/ThemeToggleButton.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,20 @@
// components/ThemeToggleButton.js
const ThemeToggleButton = () => (
<button id="darkbtn" className="daytime" title="切换模式">
<img id="icon" src="/assets/svg/moon.svg" />
//components/ThemeToggleButton.js
import React from 'react';
import { useTheme } from '../contexts/ThemeContext';
import { HiOutlineMoon, HiOutlineSun } from 'react-icons/hi';

const ThemeToggleButton = () => {
const { isDark, toggleTheme } = useTheme();

return (
<button
title="切换模式"
onClick={toggleTheme}
className="border-none bg-transparent ml-[80vw] mt-[2vh]"
>
{isDark ? <HiOutlineSun className="text-rose-500 w-6 h-6" /> : <HiOutlineMoon className="text-blue-700 w-6 h-6" />}
</button>
);

export default ThemeToggleButton;
};

export default ThemeToggleButton;
36 changes: 36 additions & 0 deletions contexts/ThemeContext.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import React, { createContext, useState, useContext, useEffect } from 'react';

const ThemeContext = createContext();

export const ThemeProvider = ({ children }) => {
const [isDark, setIsDark] = useState(false);

useEffect(() => {
const hour = new Date().getHours();
if (hour >= 21 || hour < 7) {
document.documentElement.classList.add('dark');
setIsDark(true);
} else {
document.documentElement.classList.remove('dark');
setIsDark(false);
}
}, []);

const toggleTheme = () => {
if (isDark) {
document.documentElement.classList.remove('dark');
setIsDark(false);
} else {
document.documentElement.classList.add('dark');
setIsDark(true);
}
};

return (
<ThemeContext.Provider value={{ isDark, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
};

export const useTheme = () => useContext(ThemeContext);
33 changes: 0 additions & 33 deletions lib/theme.js

This file was deleted.

0 comments on commit ca55f46

Please sign in to comment.