使用React在列表中的项目更改顺序时进行动画处理?

时间:2019-06-26 18:25:19

标签: reactjs animation

我有一个物品清单。当顺序更改时,我希望他们将其设置为新位置。

之前:

<ul>
  <li>One</li>
  <li>Two</li>
</ul>

之后:

<ul>
  <li>Two</li>
  <li>One</li>
</ul>

有没有可以做到这一点的图书馆? Ive厌倦了React Transition Group,React Pose和React Spring,但似乎都没有支持它,而是专注于在项目进入和离开DOM时的动画。我有点惊讶,我没有发现任何东西,因为这对我来说似乎是一个普通的用例。

https://reactcommunity.org/react-transition-group/

https://popmotion.io/pose/

https://www.react-spring.io/

1 个答案:

答案 0 :(得分:0)

在react-spring中有一个关于它的例子。但这很复杂,发生了很多事情。我从中创建了一个简化版本。

您有一组名称。您可以基于索引定义y值。并且您可以移动带有translate属性的元素。该位置设置为绝对。

一键点击即可对数组进行混洗。再次单击即可删除元素。在反应过渡中,您可以定义进入和离开动画。删除元素时调用的离开动画。

import { render } from 'react-dom';
import React, { useState } from 'react';
import { useTransition, animated } from 'react-spring';
import shuffle from 'lodash/shuffle';
import './styles.css';

let data = [
  {
    name: 'Rare Wind'
  },
  {
    name: 'Saint Petersburg'
  },
  {
    name: 'Deep Blue'
  },
  {
    name: 'Ripe Malinka'
  },
  {
    name: 'Near Moon'
  },
  {
    name: 'Wild Apple'
  }
];

function App() {
  const [rows, set] = useState(data);
  let height = 20;
  const transitions = useTransition(
    rows.map((data, i) => ({ ...data, height, y: i * height })),
    d => d.name,
    {
      from: { position: 'absolute', height: 20, opacity: 0 },
      leave: { height: 0, opacity: 0 },
      enter: ({ y, height }) => ({ y, height, opacity: 1 }),
      update: ({ y, height }) => ({ y, height })
    }
  );

  return (
    <div class="list" style={{ height }}>
      <button onClick={() => set(shuffle(rows))}>click</button>
      <button onClick={() => set(rows.slice(1))}>remove first</button>
      {transitions.map(({ item, props: { y, ...rest }, key }, index) => (
        <animated.div
          key={key}
          class="card"
          style={{
            zIndex: data.length - index,
            transform: y.interpolate(y => `translate3d(0,${y}px,0)`),
            ...rest
          }}
        >
          <div class="cell">
            <div class="details">{item.name}</div>
          </div>
        </animated.div>
      ))}
    </div>
  );
}

const rootElement = document.getElementById('root');
render(<App />, rootElement);

这是沙箱:https://codesandbox.io/s/animated-list-order-example-with-react-spring-teypu

编辑:我也添加了add元素,因为这是一个更好的示例。 :)

相关问题