| 1 | 'use client' |
| 2 | |
| 3 | import { useEffect, useState } from 'react' |
| 4 | |
| 5 | /** |
| 6 | * 自定义 Hook,用于获取多个 CSS 变量的值。 |
| 7 | * @param variableNames - CSS 变量名称数组(例如,['--main-color', '--secondary-color'])。 |
| 8 | * @param element - 获取 CSS 变量的元素(默认为 document.documentElement)。 |
| 9 | * @returns 一个对象,其中 CSS 变量名称作为键,变量值作为值。 |
| 10 | */ |
| 11 | function useCssVariables( |
| 12 | variableNames: string[] = [ |
| 13 | '--theColor1', |
| 14 | '--theColor2', |
| 15 | '--theColor3', |
| 16 | '--theColor4', |
| 17 | '--theColor5', |
| 18 | '--theColor6', |
| 19 | '--theColor7', |
| 20 | '--theColor8', |
| 21 | '--theColor9', |
| 22 | '--colorPrimary1', |
| 23 | '--colorPrimary2', |
| 24 | '--colorPrimary3', |
| 25 | '--colorPrimary4', |
| 26 | '--colorPrimary5', |
| 27 | '--colorPrimary6', |
| 28 | '--colorPrimary7', |
| 29 | '--colorPrimary8', |
| 30 | '--colorPrimary9', |
| 31 | ], |
| 32 | element?: HTMLElement, |
| 33 | ): Record<string, string> { |
| 34 | const [variables, setVariables] = useState<Record<string, string>>({}) |
| 35 | |
| 36 | if (typeof window === 'undefined') |
| 37 | return variables |
| 38 | |
| 39 | element = element || document.documentElement |
| 40 | |
| 41 | useEffect(() => { |
| 42 | const handleVariableChange = () => { |
| 43 | const computedStyle = getComputedStyle(element) |
| 44 | const newVariables = variableNames.reduce( |
| 45 | (acc, name) => { |
| 46 | acc[name] = computedStyle.getPropertyValue(name).trim() |
| 47 | return acc |
| 48 | }, |
| 49 | {} as Record<string, string>, |
| 50 | ) |
| 51 | |
| 52 | // 只有在变量值实际发生变化时才更新状态 |
| 53 | setVariables((prevVariables) => { |
| 54 | const hasChanged = variableNames.some(name => prevVariables[name] !== newVariables[name]) |
| 55 | return hasChanged ? newVariables : prevVariables |
| 56 | }) |
| 57 | } |
| 58 | |
| 59 | // 初始获取 |
| 60 | handleVariableChange() |
| 61 | |
| 62 | // 可选:观察元素样式的变化 |
| 63 | const observer = new MutationObserver(handleVariableChange) |
| 64 | observer.observe(element, { |
| 65 | attributes: true, |
| 66 | attributeFilter: ['style', 'class'], |
| 67 | }) |
| 68 | |
| 69 | return () => { |
| 70 | observer.disconnect() |
| 71 | } |
| 72 | }, [variableNames, element]) |
| 73 | |
| 74 | return variables |
| 75 | } |
| 76 | |
| 77 | export default useCssVariables |
| 78 |