1

我正在将应用程序从 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 来做到这一点。

4

1 回答 1

0

所以我找到了答案:

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} />;
}

于 2020-11-26T11:03:34.317 回答