首页 > 解决方案 > react-spring 等效于 react-pose PoseGroup

问题描述

当列表更改时,React Pose PoseGroup 仅使用 FlipMove 选项为列表元素设置动画

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

如何用 react-spring 做到这一点?

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

如果删除了一个项目,我想为列表设置动画,并且动画顺利填补了空白

标签: reactjsreact-springreact-pose

解决方案


在 react-spring 中动画到位置有点困难,因为您必须将位置作为样式进行操作。我喜欢使用基于钩子的动画,所以我将组件转换为函数。解决这个问题的最好方法是 react-spring 中的 useTransition 函数。您可以为它定义、输入和离开样式。并且它将应用于删除或添加的每个数组项。

对于该位置,我首先需要 y 位置作为数据,然后作为属性。所以我将索引映射为 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 })
    }
  );

然后,您可以使用渲染部分中的过渡对象来映射带有样式的项目。这里的诀窍是变换风格。y 现在根据数组顺序更改。我们可以基于它创建一个很好的变换样式来移动项目。

  <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>

最后的示例,我添加了一个添加随机播放按钮。https://codesandbox.io/s/react-spring-position-animation-di9rb


推荐阅读