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