ama*_*ann 8

Framer Motion 2.8发布了一个新animate功能,非常适合此用例:

import { animate } from "framer-motion";
import React, { useEffect, useRef } from "react";

function Counter({ from, to }) {
  const nodeRef = useRef();

  useEffect(() => {
    const node = nodeRef.current;

    const controls = animate(from, to, {
      duration: 1,
      onUpdate(value) {
        node.textContent = value.toFixed(2);
      }
    });

    return () => controls.stop();
  }, [from, to]);

  return <p ref={nodeRef} />;
}

export default function App() {
  return <Counter from={0} to={100} />;
}
Run Code Online (Sandbox Code Playgroud)

请注意,不是连续更新 React 状态,而是在我的解决方案中手动修补 DOM 以避免协调开销。

请参阅此 CodeSandbox