Persisting position of draggable Framer Motion components.

huangapple go评论57阅读模式
英文:

Persisting position of draggable Framer Motion components

问题

我正在创建一个小部件仪表板,您可以在其中移动小部件,我的目标是在拖动小部件后持久保存它们的位置,以便在将来的会话中加载到完全相同的位置。

这是一个代码示例,说明了我在使用 framer-motion 时遇到的问题:https://codesandbox.io/p/sandbox/interesting-sun-p8h6cu。

小部件的初始 topleft 值正确反映了其起始位置,但我在拖动后无法持久保存其新位置。

我在 onDragEnd 处理程序中更新了小部件的位置,然后更新了小部件上的 topleft 样式。由于 framer-motion 使用 transform: translate 应用拖动,并且定位样式的更新,这导致小部件出现以下情况:

  1. 在 onDragEnd 上正确持久保存其新位置
  2. 在前一点后在界面上发生位移,因为 top + left 样式使 transform: translate 拖动样式的效果加倍。

我不确定如何解决这个问题。我尝试过在初始定位中使用 transform: translate,但它不起作用。而且,现在我在考虑 framer-motion 会在被拖动时立即覆盖它,导致不同的不希望的行为。

简而言之:我在使用 framer-motion 的可拖动功能时遇到了显示绝对定位组件的问题。

英文:

I'm creating a widget dashboard where you can move widgets around, and my aim is to persist the widgets' positions after they are dragged, so as to load them into the exact same place in future sessions.

Here's a codesandbox that illustrates the problem I am running into with framer-motion: https://codesandbox.io/p/sandbox/interesting-sun-p8h6cu.

The initial top and left values on a widget reflect its starting position correctly, but I'm having trouble persisting its new position after dragging it.

I'm updating the widget's position in the onDragEnd handler, which in turn updates the top and left styles on the widget. With framer-motion applying the drag with transform: translate and the update of the positioning styles, this results in a widget that:

  1. has its new position persisted correctly onDragEnd
  2. is shifted in the UI after the previous point, because the top + left styles are doubling the effect of the transform: translate drag styling.

I'm not sure how to tackle this problem. I've tried using transform: translate for the initial positioning, but it doesn't work. Plus, now I'm thinking that framer-motion would override it as soon as it gets dragged, resulting in a different unwanted behavior.

TLDR: I'm having trouble displaying absolutely positioned components that are draggable with framer-motion's drag feature

答案1

得分: 0

你说得对,topleft 之所以会重复,是因为 Framer 拖动功能改变了 xy。如果你只改变 xy,一切应该保持同步。

style={{ x: widget.x, y: widget.y }}

而不是

style={{ left: widget.x, top: widget.y }}
英文:

You're right that top and left are getting doubled up because the Framer drag functionality is altering the x and y. Since you then apply that xy transform to the top and left, you're getting unexpected results.

If you instead only alter the x and y, everything should stay in sync.

style={{ x: widget.x, y: widget.y }}

instead of

style={{ left: widget.x, top: widget.y }}

huangapple
  • 本文由 发表于 2023年5月7日 15:36:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76192693.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定