跳到主要内容

useRafState

requestAnimationFrame 更新状态。

Usage

实时编辑器

function Demo() {
  const [state, setState] = useRafState({ x: 0, y: 0 });

  useMount(() => {
    const onMouseMove = (event: MouseEvent) => {
      setState({ x: event.clientX, y: event.clientY });
    };
    const onTouchMove = (event: TouchEvent) => {
      setState({
        x: event.changedTouches[0].clientX,
        y: event.changedTouches[0].clientY,
      });
    };

    document.addEventListener("mousemove", onMouseMove);
    document.addEventListener("touchmove", onTouchMove);

    return () => {
      document.removeEventListener("mousemove", onMouseMove);
      document.removeEventListener("touchmove", onTouchMove);
    };
  });

  return <pre>{JSON.stringify(state, null, 2)}</pre>;
};

结果
Loading...

API

useRafState

Returns

readonly [S, React.Dispatch<React.SetStateAction<S>>]: 包含以下元素的元组:

  • state 的当前值。
  • requestAnimationFrame 中更新 state 值的函数。

Arguments

参数名描述类型默认值
initialState状态值S | (() => S) (必填)-