【问题标题】:Framer motion - animation doesn't start after state change using controlsFramer 运动 - 使用控件更改状态后动画不会开始
【发布时间】:2021-12-15 16:51:13
【问题描述】:

我为图像滑块制作了自定义点,通常效果很好。点会触发图像滑块动画,但现在我必须在幻灯片悬停时暂停点。我的问题是第一个点在第一次加载时动画然后它什么都不做,直到我将鼠标悬停在幻灯片上它会继续然后再次停止。

如果没有控件,它们可以完美运行。

我不确定问题出在我的组件中。

这里有一个code sandbox 来说明问题。

export const TimerDots = ({
  pauseDots,
  amount,
  duration,
  handleChange,
  activeIndex
}: {
  pauseDots?: boolean;
  amount: number;
  duration: number;
  handleChange: (e: any) => void;
  activeIndex: number;
}) => {
  const controls = useAnimation();

  const handleNextSlide = () => {
    handleChange((activeIndex += 1));
  };

  const startAnimation = controls.start({
    width: SIZE * 3,
    transition: {
      duration: duration,
      type: "tween",
      ease: "easeOut"
    }
  });

  useEffect(() => {
    startAnimation;

    if (pauseDots) {
      controls.stop();
    }
  }, [pauseDots, activeIndex]);

  return (
    <DotContainer amount={amount}>
      {[...Array.from({ length: amount })].map((_, index) => {
        return (
          <Dot
            layout
            key={index}
            onClick={() => handleChange(index)}
            $active={activeIndex === index}
          >
            {activeIndex === index && (
              <Timer
                layout
                animate={controls}
                onAnimationComplete={handleNextSlide}
              />
            )}
          </Dot>
        );
      })}
    </DotContainer>
  );
};

【问题讨论】:

    标签: reactjs framer-motion


    【解决方案1】:

    问题来自startAnimation以及它在useEffect中是如何使用的

    当您在useEffect 中执行startAnimation 时,您不会调用函数controls.start(..)

    试试这个:

    
    const startAnimation = () => {
        controls.start({
          width: SIZE * 3,
          transition: {
            duration: duration,
            type: "tween",
            ease: "easeOut"
          }
        });
      };
    
      useEffect(() => {
        startAnimation();
    
        if (pauseDots) {
          controls.stop();
        }
      }, [pauseDots, activeIndex, controls]);
    

    CodeSandbox.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2019-09-23
      • 1970-01-01
      • 2011-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多