useCssVar
管理 CSS 变量
Usage
实时编辑器
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}> Sample text, <>{color}</> </div> <button onClick={switchColor}>Change Color</button> </section> ); }
结果
Loading...
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;