简体   繁体   English

Framer Motion 返回拖动按钮

[英]Framer Motion return drag button

I have objects that can be moved using drag on framer motion.我有可以使用成帧器运动拖动来移动的对象。 How can I make a button to return all elements to their initial position?我怎样才能制作一个按钮将所有元素返回到它们的初始 position?

I tried to do it with animate, but the animation is sharp and ugly.我试着用动画来做,但 animation 又尖又丑。 I think this is because when you release the element, it still some time "floats" in space and after the animation continues to do so.我认为这是因为当你释放元素时,它仍然会在空间中“漂浮”一段时间,并且在 animation 继续这样做之后。

You can use the useTransform hook in Framer Motion.您可以在 Framer Motion 中使用useTransform钩子。 You can set the initial position of each element using the initial prop and then use the useTransform hook to update the position of each element based on the state of the button.您可以使用 initial 属性设置每个元素的初始 position,然后使用useTransform钩子根据按钮的 state 更新每个元素的 position。

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

const MyComponent = () => {
const [isReset, setIsReset] = useState(false);

const x = useTransform(isReset, [false, true], [0, 100]);
const y = useTransform(isReset, [false, true], [0, 100]);

return (
    <>
      <motion.div
        drag
        style={{ x, y }}
        transition={{ duration: 0.5, ease: "easeInOut" }}
      />
      <button onClick={() => setIsReset(true)}>Reset</button>
    </>
  );
};

export default MyComponent;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM