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}> 示例文本,<>{color}</> </div> <button onClick={switchColor}>更改顏色</button> </section> ); }
結果
示例文本,#7fa998
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;