如何在React中为条件元素制作动画

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

              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的animation.div没有设置相同的动画。正确的方法是什么?有没有办法在没有反应弹簧的情况下对其进行动画处理?

2)我有一个基于标志的条件引导类名。我要设置动画

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

为此,问题在于它没有动画。正确的方法是什么?

js20090617 回答:如何在React中为条件元素制作动画

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

您的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。

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

本文链接:https://www.f2er.com/3085377.html

大家都在问