css - 如何在 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>
同样,问题在于它不是动画。什么是正确的方法?
解决方案
你有很多问题。我可以回答一部分,也许你会更好地理解它。
您的 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。
也许它也回答了你的第二个问题。我不熟悉引导程序。
推荐阅读
- r - 来自 chisq.test 的 p 值矩阵
- git - 无法将 git 更改推送到远程
- arrays - 需要帮助过滤数组?
- javascript - 在 CSS 中显示悬停状态时遇到问题
- .net - 从 CefSharp 中的 iframe 返回 .net 调用被阻止
- mongodb - 如何访问 MongoDB 数据?
- python - 根据当前时间更改变量
- python - 根据另一个系列中字符串中的值的计数,将布尔值分配给熊猫数据框中的空白系列/
- gradle - project.getProperty() 如何在 Gradle 中工作?
- python - 为什么我的 Python 代码仅适用于特定输入?