反应:成帧器运动/ onClick仅激活动画

问题描述

我正在尝试使用Framer Motion制作图像动画:

utils / MonkeyPicture.js

import React from 'react';

const MonkeyPic = () => {

        return (
            <div>               
                  <img
                    transition={{ duration: 0.5 }}
                    animate={{ rotate: [0,-30,0]}}
                    id='monkeyFace'
                    src='/images/Monkey.png' />
                               
            </div>);         
}
export default MonkeyPic; 

所以我需要一个添加或激活属性函数: 过渡= {{持续时间:0.5}} animate = {{旋转:[0,-30,0]}} 当我点击一个按钮时。

图片始终被渲染,我只想在单击按钮时旋转它。

onClick方法位于AddTodo.js容器中:

            <button id='addTodo' onClick={() => {
                monkeySound.play(); 
                setShowFistBump(true);
                setTimeout(() => { 
                    setShowFistBump(false);
                },1000);

解决方法

例如,您可以使用variants

// First pass rotate prop to MonkeyPic component inside your AddTodo
// You can use existing showFistBump state for that

<MonkeyPic rotate={showFistBump} />

// ...

// Then switch animation variant depending on rotate prop

const variants = {
  rotate: { rotate: [0,-30,0],transition: { duration: 0.5 } },// You can do whatever you want here,if you just want it to stop completely use `rotate: 0`
  stop: { y: [0,-10,transition: { repeat: Infinity,repeatDelay: 3 } }
};

const MonkeyPic = ({ rotate }) => {
  return (
    <div>
      <motion.img
        variants={variants}
        animate={rotate ? 'rotate' : 'stop'}
        id="monkeyFace"
        src="/images/Monkey.png"
      />
    </div>
  );
};

Codesandbox链接:https://codesandbox.io/s/httpsstackoverflowcomquestions63864386-rd1xh?file=/src/utils/MonkeyPicture.js