跳到主要内容

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属性值,比如 --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;