useCssVar
管理 CSS 变量
useCssVar 用于读写目标 DOM 元素上的 CSS 自定义属性(变量)。它返回一个包含当前变量值和设置函数的元组。可选地,它可以通过 MutationObserver 监听变化,以便在外部代码修改变量时保持返回值同步。
使用场景
- 在运行时通过读写 CSS 自定义属性来动态设置组件主题
- 构建颜色选择器或样式编辑器,操作特定元素上的 CSS 变量
- 将 React 状态与 CSS 变量同步,用于动画或过渡效果
注意事项
- SSR 安全:在服务端渲染期间返回提供的默认值和空操作设置函数。服务端不会访问 DOM。
- MutationObserver:在选项中设置
observe: true可通过 MutationObserver 自动跟踪 CSS 变量的外部变化。 - 目标元素:该 hook 需要一个指向特定 DOM 元素的 ref;变化范围限定在该元素的内联样式中。
Usage
Live Editor
function Demo() { const key = "--color"; const ref = useRef<HTMLDivElement>(null); const [color, setColor] = useCssVar(key, ref, ""); const style: any = { "--color": "#7fa998", "color": "var(--color)", }; const switchColor = () => { if (color === "#df8543") { setColor("#7fa998"); } else { setColor("#df8543"); } }; return ( <section> <div ref={ref} style={style}> 示例文本, <>{color}</> </div> <button onClick={switchColor}>更改颜色</button> </section> ); }
Result
API
useCssVar
Returns
readonly [string, (v: string) => void]: 包含以下元素的元组:
- css 变量值
- 更新 css 变量值的函数
Arguments
| 参数名 | 描述 | 类型 | 默认值 |
|---|---|---|---|
| prop | 属性值,比如 --color | string (必填) | - |
| target | dom元素 | BasicTarget<T> (必填) | - |
| defaultValue | 默认值 | string | undefined | - |
| options | 可选项 | UseCssVarOptions | undefined | - |
UseCssVarOptions
| 参数名 | 描述 | 类型 | 默认值 |
|---|---|---|---|
| observe | 使用 MutationObserver 来监听变量变更 | boolean | false |
BasicTarget
export type BasicTarget<T extends TargetType = Element> = (() => TargetValue<T>) | TargetValue<T> | MutableRefObject<TargetValue<T>>;
TargetValue
type TargetValue<T> = T | undefined | null;
TargetType
type TargetType = HTMLElement | Element | Window | Document | EventTarget;