【问题标题】:How to stop a css animation in react [duplicate]如何在反应中停止css动画[重复]
【发布时间】:2021-03-30 16:48:55
【问题描述】:

我有一个问题,我让我的 img 连续 360 度旋转,但我希望它只在播放音乐时这样做。我将 isPlaying 的值传递给函数,但我不知道如何从 React 访问 CSS 值。

import React from "react";

const Song = ({ currentSong, isPlaying }: any) => {
  return (
    <div className="song-container">
      <img id="image" alt={currentSong.name} src={currentSong.cover}></img>
      <h2>{currentSong.name}</h2>
      <h3>{currentSong.artist}</h3>
    </div>
  );
};

export default Song;

这是我的 CSS 文件:

.song-container {
  min-height: 70vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  img {
    width: 40%;
    border-radius: 50%;
    animation: spin 10s linear infinite;
    animation-play-state: paused;
  }
  @keyframes spin {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }
  h2 {
    padding: 3rem 1rem 1rem 1rem;
    font-size: 3rem;
  }
  h3 {
    font-size: 1.5rem;
  }
}

我希望能够在状态未播放时停止它,而当它正在播放时,我希望动画播放。我也在使用打字稿,因为我想学习这门语言,但如果实施起来太困难,我只会将我的网站转换为 javascript。

【问题讨论】:

  • 我似乎已经找到了使用 但这不是最漂亮的解决方案,我很想听听你们是否有更好的解决方案

标签: reactjs typescript


【解决方案1】:

有两种方法可以做到这一点:内联样式和切换一些 CSS 类。

对于内联样式方法,你应该为img元素设置style属性,并且属性应该是驼峰式的:

<img id="image" alt={currentSong.name} src={currentSong.cover} style={{ animationPlayState: isPlaying ? "running" : "paused" }} />

对于类切换方法,您应该在 CSS 中创建一个更改动画状态的类。

例如,在 CSS 中:

img.animate {
  animation-play-state: running;
}

然后,在img 元素中:

<img id="image" alt={currentSong.name} src={currentSong.cover} className={isPlaying ? "animate" : undefined} />

切换类是一种最佳做法,但当样式基于您无法预测的动态值时,两者都会起作用,并且内联样式会更好。


参考:https://reactjs.org/docs/dom-elements.html#style

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-29
    • 2018-03-22
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多