【问题标题】:Animate when items in a list change order with React?当列表中的项目使用 React 更改顺序时制作动画?
【发布时间】:2019-11-08 18:20:47
【问题描述】:

我有一个物品清单。当顺序发生变化时,我希望他们动画到他们的新位置。

之前:

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

之后:

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

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

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

https://popmotion.io/pose/

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

【问题讨论】:

标签: reactjs animation


【解决方案1】:

在 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 元素,因为这是一个更好的例子。 :)

【讨论】:

  • 您能否更新以使用 Spring 版本 9? usetransition 有点改变。
猜你喜欢
  • 1970-01-01
  • 2020-07-04
  • 1970-01-01
  • 2023-03-23
  • 2023-02-17
  • 2019-02-06
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
相关资源
最近更新 更多