【问题标题】:Why does this react-spring animation change its margin-top during an animation?为什么这个 react-spring 动画在动画期间会改变它的 margin-top?
【发布时间】:2020-11-22 17:55:19
【问题描述】:

我有一个 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

【问题讨论】:

    标签: reactjs react-spring


    【解决方案1】:

    这不是您看到的边距顶部。它是旧组件向左侧移动并改变不透明度,但它仍然存在。最后,它在新组件处于垂直位置的那一刻被卸载。大多数时候,我们使用绝对位置,新旧组件相互重叠。这样,卸载时就没有颠簸。像这样的:

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

    【讨论】:

    • 感谢它的工作!但是,React 声称它无法对未安装的组件执行更新,这意味着这个小脚本中存在内存泄漏。它必须来自 React Spring 动画,因为没有别的了。你也知道如何解决这个漏洞吗?
    • 我发现了一个问题 (github.com/pmndrs/react-spring/issues/906)。它说类似的问题在版本 9 中起作用。我尝试使用随机版本(9.0.0-beta.2)并且它没有问题。我不知道该推荐什么。版本号令人困惑。要么你选择它工作的最高 beta 数字,要么你可以使用最新的 rc.3,但你必须重构你的代码,因为它使用稍微不同的 api。或者您稍等一下最终版本 9。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 2014-04-12
    • 1970-01-01
    • 2020-02-20
    • 2014-05-17
    • 2019-07-14
    相关资源
    最近更新 更多