当列表中的项目使用 React 更改顺序时动画?

Eva*_*nss 6 animation reactjs

我有一个物品清单。当订单改变时,我希望他们动画到他们的新位置。

前:

<ul>
  <li>One</li>
  <li>Two</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

后:

<ul>
  <li>Two</li>
  <li>One</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

有没有可以做到这一点的图书馆?我已经厌倦了 React Transition Group、React Pose 和 React Spring,但似乎没有一个支持它,相反,它们专注于项目进入和离开 DOM 时的动画。我有点惊讶我没有找到任何东西,因为这对我来说似乎是一个常见的用例。

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

https://popmotion.io/pose/

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

Pet*_*uzs 12

在 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);
Run Code Online (Sandbox Code Playgroud)

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

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

  • 你好@amin-noura,我在这里更新为使用 `react-spring` 版本 9。https://codesandbox.io/s/animated-list-order-example-with-react-spring-forked-nhwqk9?file=/src/index.js (2认同)