首页 > 解决方案 > 如何在 React 中为条件元素设置动画

问题描述

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

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

              /***
              Some code
              ***/

              const styleProps = useSpring({
                 to: { opacity: 1 },
                 from: { opacity: 0 }
              });

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

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

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

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

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

同样,问题在于它不是动画。什么是正确的方法?

标签: cssreactjsanimationbootstrap-4react-spring

解决方案


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

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

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

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

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

    <animated.div style={styleProps2}>
      To appear with animation
    </animated.div>
  </>
</section>

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

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

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


推荐阅读