From a6e344135df2895e4da4d4afdd1ce7f1734103ef Mon Sep 17 00:00:00 2001 From: Jiaxin Peng <83734772+jxpeng98@users.noreply.github.com> Date: Fri, 21 Jul 2023 18:57:28 +0100 Subject: [PATCH] Create DarkModeButton.js add darkmodebutton --- themes/heo/components/DarkModeButton.js | 38 +++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 themes/heo/components/DarkModeButton.js diff --git a/themes/heo/components/DarkModeButton.js b/themes/heo/components/DarkModeButton.js new file mode 100644 index 00000000..9b56e6da --- /dev/null +++ b/themes/heo/components/DarkModeButton.js @@ -0,0 +1,38 @@ +import { useGlobal } from '@/lib/global' +import { saveDarkModeToCookies } from '@/themes/theme' +import { Moon, Sun } from '@/components/HeroIcons' +import { useImperativeHandle } from 'react' + +/** + * 深色模式按钮 + */ +const DarkModeButton = (props) => { + const { cRef, className } = props + const { isDarkMode, updateDarkMode } = useGlobal() + + /** + * 对外暴露方法 + */ + useImperativeHandle(cRef, () => { + return { + handleChangeDarkMode: () => { + handleChangeDarkMode() + } + } + }) + + // 用户手动设置主题 + const handleChangeDarkMode = () => { + const newStatus = !isDarkMode + saveDarkModeToCookies(newStatus) + updateDarkMode(newStatus) + const htmlElement = document.getElementsByTagName('html')[0] + htmlElement.classList?.remove(newStatus ? 'light' : 'dark') + htmlElement.classList?.add(newStatus ? 'dark' : 'light') + } + + return