简体   繁体   English

react-spring 相当于 react-pose PoseGroup

[英]react-spring equivalent of react-pose PoseGroup

React Pose PoseGroup simply animates elements of a list when the list change with the flipMove option当使用 flipMove 选项更改列表时,React Pose PoseGroup 简单地为列表的元素设置动画

https://codesandbox.io/s/inspiring-herschel-37bvs https://codesandbox.io/s/inspiring-herschel-37bvs

How to do it with react-spring?如何用react-spring做到这一点?

{items.map(item => (
    <Item key={item} />
  ))}

I'd like to animate the list if an item is removed, and the animation smoothly fill the gap如果删除了一个项目,我想为列表设置动画,并且动画平滑地填补了空白

Animating to position is a little more difficult in react-spring, as you have to manipulate the positions as styles.在 react-spring 中为位置设置动画有点困难,因为您必须将位置作为样式来操作。 I like to use hook based animation so I converted the component to function.我喜欢使用基于钩子的动画,所以我将组件转换为函数。 The best way to solve this problem is the useTransition function in react-spring.解决这个问题最好的方法就是react-spring中的useTransition函数。 You can define from, enter and leave styles for it.您可以为其定义 from、enter 和 leave 样式。 And it will apply to each array item as they removed or added.它将应用于删除或添加的每个数组项。

For the position I need the y position first as data then as a property.对于位置,我首先需要 y 位置作为数据,然后作为属性。 So I map the index as y, and I introduce it to the props as a variable to interpolate from.因此,我将索引映射为 y,并将其作为要从中进行插值的变量引入道具。

  const [items, setItems] = React.useState([0, 1, 2, 3]);

  const transitions = useTransition(
    items.map((item, i) => ({ label: item, y: i })),
    item => item.label,
    {
      from: { opacity: 0 },
      leave: { opacity: 0 },
      enter: ({ y }) => ({ y, opacity: 1 }),
      update: ({ y }) => ({ y })
    }
  );

Then you can use the transition object in the render part to map the items with styles from it.然后你可以在渲染部分使用过渡对象来映射带有样式的项目。 The trick here is the transform style.这里的技巧是转换样式。 The y now change based on the array order. y 现在根据数组顺序更改。 We can create a nice transform style based on it to move the items around.我们可以基于它创建一个漂亮的变换样式来移动项目。

  <ul className="sidepanel">
    {transitions.map(({ item, props, key }, index) => (
      <animated.li
        style={{
          position: "absolute",
          opacity: props.opacity,
          transform: props.y.interpolate(
            y => `translate3d(0,${y * 40}px,0)`
          )
        }}
        className="item"
        data-key={item.label % 5}
        key={key}
        onClick={() => {
          setItems([0, 1, 3]);
        }}
      />
    ))}
  </ul>

Finally the example, I added an add an shuffle button.最后的例子,我添加了一个添加随机播放按钮。 https://codesandbox.io/s/react-spring-position-animation-di9rb https://codesandbox.io/s/react-spring-position-animation-di9rb

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

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