为什么这个 react-spring 动画会在动画期间改变它的 margin-top?

Why does this react-spring animation change its margin-top during an animation?

我有一个 react-spring 动画,它包含使组件在滑动时出现。但是在这个动画期间,组件在恢复正常之前改变了它的边距顶部。如何解决这个问题?

这是代码和沙箱:

import React, { useEffect, useMemo, useState } from "react";
import styled, { css, keyframes } from "styled-components";
import { animated, useTransition } from "react-spring";

const Tabs = styled.div`
  display: flex;
  margin-bottom: 12px;
`;

const Tab = styled.button<{ active: boolean }>`
  margin: 0 4px;
  border-bottom: 1px solid transparent;
  font-weight: ${({ active }) => active && 600};
  cursor: pointer;
  background: transparent;
  border: 0;
  &:focus {
    outline: none !important;
  }
`;

export default function Inbox() {
  const [tab, setTab] = useState(0);

  const transitions = useTransition(tab, (p) => p, {
    from: { opacity: 0, transform: "translate3d(100%,0,0)" },
    enter: { opacity: 1, transform: "translate3d(0%,0,0)" },
    leave: { opacity: 0, transform: "translate3d(-50%,0,0)" }
  });

  const getList = (name: string) => <div>{name}</div>;

  const pages = [
    ({ style }) => (
      <animated.div style={style}>{getList("test 1")}</animated.div>
    ),
    ({ style }) => (
      <animated.div style={style}>{getList("test 2")}</animated.div>
    )
  ];

  return (
    <>
      <Tabs>
        <Tab onClick={() => setTab(0)} active={tab === 0}>
          Unread
        </Tab>
        <Tab onClick={() => setTab(1)} active={tab === 1}>
          All
        </Tab>
      </Tabs>
      {transitions.map(({ item, props, key }) => {
        const Page = pages[item];
        return <Page key={key} style={props} />;
      })}
    </>
  );
}

沙盒:https://codesandbox.io/s/amazing-ride-hwbv2?file=/src/App.tsx

不是你看到的margin top。它是旧组件向左侧移动并改变不透明度,但它仍然存在。最后,在新组件占据其垂直位置的那一刻,它被卸载了。大多数时候我们使用绝对定位,即新旧组件彼此重叠。这样在卸载时就没有颠簸。像这样:

from: { opacity: 0, transform: "translate3d(100%,0,0)", position: "absolute" },