在我的React应用程序中,我试图淡入div,稍等片刻,然后使其淡出。除了淡出以外,一切工作正常。 我的SCSS看起来像这样:
$orange-color: #DD7C15;
$white-color: #FFFFFF;
$black-color: #222222;
.App {
font-family: sans-serif;
text-align: center;
}
.message-banner {
position: fixed;
bottom: 0;
left: 0;
z-index: 100000;
width: 100vw;
color: $orange-color;
font-size: 4em;
text-align: center;
background-color: $white-color;
border: 2px solid $black-color;
opacity: 0.9;
animation: fadeIn 2s ease-in;
&.hide {
opacity: 0;
animation: fadeOut 2s ease-out;
}
}
@keyframes fadeIn {
0% {
opacity: 0;
}
100% {
opacity: 0.9;
}
}
@keyframes fadeOut {
0% {
opacity: 0.9;
}
100% {
opacity: 0;
}
}
和我相关的React代码:
const showBanner = () => {
setMessageBannerText("My sweet awesome banner!!");
setTimeout(() => {
setMessageBannerText("");
}, 3000);
};
const bannerClasses =
messageBannerText === "" ? "message-banner hide" : "message-banner";
我创建了一个沙箱,用于显示我在说什么。 https://codesandbox.io/s/brave-grass-q1y6j
答案 0 :(得分:2)
问题:
动画效果很好,但是您正在删除动画中的内容setMessageBannerText("");
,因此它不可见
解决方案:
因此,您应该保持动画的状态,而不是将内容保留为空白
1)解决方案:
const steps = {
0: "", // <--- blank coz message-banner has animation itself
1: "message-banner",
2: "message-banner hide"
};
export default function App() {
const messageBannerText = "My sweet awesome banner!!";
const [animationStep, setAnimationStep] = useState(0);
const showBanner = () => {
setAnimationStep(1);
setTimeout(() => {
// setMessageBannerText(""); // <---- issue
setAnimationStep(2);
}, 3000);
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={showBanner}>Show Banner</button>
<MessageBanner text={messageBannerText} classes={steps[animationStep]} />
</div>
);
}
工作演示:
2)解决方案:(具有CSS更改,但您仍需要遵循上述更改)
.message-banner {
position: fixed;
bottom: 0;
left: 0;
z-index: 100000;
width: 100vw;
color: $orange-color;
font-size: 4em;
text-align: center;
background-color: $white-color;
border: 2px solid $black-color;
opacity: 0;
&.animate {
opacity: 0;
animation: fadeInOut 5s ease-out;
}
}
// single animation for fade in and fade out
@keyframes fadeInOut {
0% {
opacity: 0;
}
30% {
opacity: 0.9;
}
70% {
opacity: 0.9;
}
100% {
opacity: 0;
}
}
const [show, setShow] = useState(false);
const showBanner = () => {
if (!show) { // <--- just for safe side, if animation is going on, then ignore state change
setShow(true);
setTimeout(() => {
setShow(false);
}, 5000);
}
};
const bannerClasses = show ? "message-banner animate" : "message-banner";
工作演示:
答案 1 :(得分:1)