React-淡入div,暂停并淡出div

问题描述 投票:0回答:1

在我的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

css reactjs fadein fadeout
1个回答
0
投票

问题:

动画效果很好,但是您正在删除动画中的内容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>
  );
}

工作演示:

Edit #SO-animate-issue2


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";

工作演示:

Edit #SO-animate-issue

© www.soinside.com 2019 - 2024. All rights reserved.