如何在成帧器运动中多次使用动画

问题描述 投票:0回答:2

就像标题一样,我试图在单击按钮时多次为我的组件设置动画。目前,动画只运行一次,然后就不再起作用了,我怎么可能实现它

这是我正在尝试做的一个例子:

const controls = useAnimation();

    const handleClick = (e) => {
        controls.start({
            rotate: "360deg",
        });
    };

return(
<motion.button onClick={handleClick}>Button</motion.button>
<motion.div className="someRect" animate={controls}></motion.div>
)
javascript reactjs animation next.js framer-motion
2个回答
3
投票

说实话,我从未使用过 useAnimation 控件,所以我不知道这里发生了什么以及如何使用你的方法来解决这个障碍,但你可能会通过这样的东西实现你所追求的目标。

  <button onClick={() => setRotate((prevState) => prevState + 360)}>
    Button
  </button>
  <motion.div
    className="someRect"
    animate={{
      rotate: rotate,
      transition: { duration: 3 }
    }}
    style={{ width: "100px", height: "100px", background: "red" }}
  >
  </motion.div>

我知道这个解决方案并不是最佳的,因为状态随着每次点击而不断增长,可能会变得非常大,这可能会在某些时候导致问题。

在这个CodeSanbox

中检查我的解决方案

希望也许有人会想出一个更优雅的解决方案,我也很高兴看到。


0
投票

我今天实际上遇到了同样的问题,所以决定在这里发帖,以防有人想知道该怎么做。

使用新的

useAnimate
钩子,我们可以在动画结束后将旋转更改回 0。

import "./styles.css";
import { useAnimate } from "framer-motion";

export default function App() {
  const [scope, animate] = useAnimate();

  const handleRotate = () => {
    animate(
      scope.current,
      { rotate: 180 },
      {
        duration: 0.5,
        onComplete() {
          animate(scope.current, { rotate: 0 }, { duration: 0 });
        },
      }
    );
  };

  return (
    <div className="App">
      <button onClick={handleRotate}>Rotate square</button>
      <div ref={scope} className="square" />
    </div>
  );
}

这是带有实现的代码沙箱

© www.soinside.com 2019 - 2024. All rights reserved.