跳至主要内容

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属性值,比如 --colorstring (必填)-
targetdom元素BasicTarget<T> (必填)-
defaultValue默认值string | undefined-
options可选项UseCssVarOptions | undefined-

UseCssVarOptions

參數名描述類型預設值
observe使用 MutationObserver 来监听变量变更booleanfalse

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;