reactjs React:Framer Motion / onClick仅激活动画

kokeuurv  于 2023-02-03  发布在  React
关注(0)|答案(2)|浏览(155)

我正在尝试使用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 }}动画={{旋转:[0,-30,0]}}单击按钮时。
图片是渲染的整个时间,我只是希望旋转它,当我点击一个按钮。
onClick方法位于AddTodo.js容器中:

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

mnemlml81#

你可以使用variants,例如:

// At first you need to pass `rotate` prop to MonkeyPic component inside your AddTodo
// You can use existing showFistBump state for that

<MonkeyPic rotate={showFistBump} />

// ...

// In the component create variants of your animation state
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, 0], transition: { repeat: Infinity, repeatDelay: 3 } }
};

// Then switch animation variant depending on that `rotate` prop

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

代码沙箱链接:https://codesandbox.io/s/httpsstackoverflowcomquestions63864386-rd1xh?file=/src/utils/MonkeyPicture.js

iqxoj9l9

iqxoj9l92#

在React中,更改元素的键会使React将其视为一个全新的组件。
尽管framer为我们提供了三种类型的动画用例
1.输入动画{组件渲染时}
1.退出动画{当组件即将离开dom树时}
1.基于手势的动画
然而,缺少类似的触发动画,这将帮助我们在需要时播放动画,但无论如何,我们将使用感兴趣的组件的关键属性,并将其值设置为ref,然后触发它,我们将更改ref的值,以便每次重新呈现组件并播放入口动画时,示例都转换理论

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

function ShakingButton({
  children,
  className,
  onClick,
}: {
  onClick?: React.MouseEventHandler<HTMLDivElement>;
  children: React.ReactNode;
  className: string;
}) {
  
  const ref = useRef(0);
  return (
    <motion.div
      key={ref.current}
      animate={ref.current === 0 ? {} : {
        x : [0, 10,-10,0]
      }}
      transition={{
        type: "spring",
      }}
      onClick={(e) => {
        onClick && onClick(e);
        ref.current++;
      }}
      className={className}
    >
      {children}
    </motion.div>
  );
}

export default ShakingButton;

相关问题