【问题标题】:How to animate conditional elements in React如何在 React 中为条件元素设置动画
【发布时间】:2020-03-13 04:06:10
【问题描述】:

我有一个 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 动画不一样。什么是正确的方法?有没有办法在没有 react-spring 的情况下制作相同的动画?

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

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

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

【问题讨论】:

    标签: css reactjs animation bootstrap-4 react-spring


    【解决方案1】:

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

    您的 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 }
    });
    
    <section>
      <>
        <animated.div style={styleProps1}>
          Some random text
        </animated.div>
    
        <animated.div style={styleProps2}>
          To appear with animation
        </animated.div>
      </>
    </section>
    

    如果你想让元素出现在同一个地方,你必须使用绝对定位。

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

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

    【讨论】:

    • 感谢@Peter Ambruzs。绝对位置和 useTransition 工作。条件 className 仍然是一个问号。根据一个条件,我想要类名上的类似转换
    • 我不确定第二个问题你想要什么。我猜您想在类名更改时重新触发动画。我说的对吗?
    • 是的@Peter Ambruzs,基本上 col-lg-6 所做的是将宽度设置为 50%,而 col-lg-12 所做的是将宽度设置为 100%。所以,我想要从 50 到 100% 的宽度动画
    • 你不能基于带有 react-spring 的类制作动画。您可以将宽度更改移动到 useSpring 或添加 CSS 动画,如下所示:w3schools.com/css/tryit.asp?filename=trycss3_transition1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    相关资源
    最近更新 更多