如何在 React 中为条件元素设置动画

Bij*_*pil 0 css animation reactjs bootstrap-4 react-spring

我有一个 React 应用程序。我正在使用 React Spring 来制作整体动画。我无法为两件事制作动画 - 我正在试验的动画是一个简单的不透明动画。

              import { useSpring, animated } from "react-spring";

              /***
              Some code
              ***/

              const styleProps = useSpring({
                 to: { opacity: 1 },
                 from: { opacity: 0 }
              });
Run Code Online (Sandbox Code Playgroud)

1) 是条件元素。请参考以下代码 -

              <section>
                {!flag ? (
                <animated.div style={styleProps}>
                  Some random text
                </animated.div>
              ) : (
                <animated.div style={styleProps}>
                  To appear with animation
                </animated.div>
              )
             }
             </section>
Run Code Online (Sandbox Code Playgroud)

问题是react-spring 的animated.div 的动画不一样。什么是正确的方法?有没有办法在没有反应弹簧的情况下制作相同的动画?

2)我有一个基于标志的条件引导类名。我想制作相同的动画

            <animated.div style={styleProps} className={classnames({
                 "col-lg-6": !flag,
                 "col-lg-12": flag
            })}
            >
                Random Content
            </animated.div>
Run Code Online (Sandbox Code Playgroud)

对于这一点,问题在于它没有动画。什么是正确的方法?

Pet*_*uzs 5

哟有很多问题。我可以回答一部分,也许你会更好地理解它。

您的 useSpring 动画示例仅触发一次。当您使用条件渲染在组件之间切换时,它将不再有动画效果。

但是您可以在 useSpring 中重新触发动画,如果您有条件地更改 'to' 参数(并将渲染留给 react-spring)。

const styleProps1 = useSpring({
   to: { opacity: flag ? 1 : 0 },
   from: { opacity: 0 }
});

const styleProps2 = useSpring({
   to: { opacity: flag ? 0 : 1 },
   from: { opacity: 0 }
});
Run Code Online (Sandbox Code Playgroud)
<section>
  <>
    <animated.div style={styleProps1}>
      Some random text
    </animated.div>

    <animated.div style={styleProps2}>
      To appear with animation
    </animated.div>
  </>
</section>
Run Code Online (Sandbox Code Playgroud)

如果您希望元素出现在同一位置,则必须使用绝对定位。

使用 useTranstion 也可以使用绝对定位实现类似的效果。在这种情况下,元素在动画结束时卸下。因此,如果您在使用 useSpring 方法时遇到鼠标单击问题,您可以尝试切换到 useTransition。

也许它也能回答你的第二个问题。我对引导程序不熟悉。