如何使用 Framer Motion 为数字制作动画?

How to animate number with Framer Motion?

我正在将一个应用程序从 react-spring 迁移到 framer-motion。使用 Spring,我可以为数字设置动画:

export default function MyNumber({ number }) {
  const spring: any = useSpring({ from: { number: 0 }, to: { number } });
  return (
    <animated.div>
      {spring.number.interpolate((c) => c.toFixed(1))}
    </animated.div>
  );
}

我不知道如何使用 Framer-Motion。

所以我找到了答案:

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

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

  useEffect(() => {
    const controls = animate(from, to, {
      duration: 1,
      onUpdate(value) {
        ref.current.textContent = value.toFixed(1);
      }
    });
    return () => controls.stop();
  }, [from, to]);

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

export default function App() {
  return <Counter from={0} to={65.4} />;
}