【问题标题】:React - Reset css animation in progressReact - 重置 css 动画正在进行中
【发布时间】:2018-03-19 07:36:37
【问题描述】:

在 React 中,如果我有一个基于按钮单击开始的动画,我如何重新启动该动画?

jsx

const animationStyle = `countdown ${this.props.duration}s linear infinite forwards`;


<svg id="svg1">
  <circle
    id="c1"
    style={{animation: animationStyle }}
    cx="100"
    cy="100"
    r="80"
  ></circle>
</svg>

.css 文件

@keyframes countdown {
  from {
    stroke-dashoffset: 0px;
  }
  to {
    stroke-dashoffset: 500px;
  }
}

如果我传递一个新的持续时间,它不会立即开始新的动画。

【问题讨论】:

    标签: css reactjs animation


    【解决方案1】:

    我认为您需要在更新持续时间时删除 svg 圆圈并重新添加它才能重置动画。

    因此,在反应中,您可以通过保留一个名为 resetAnimation 的状态变量并在更新持续时间之前将值更改为 true 这将强制组件呈现然后在 setState 的回调函数中将 resetAnimation 还原为 false再次更新持续时间。

    检查以下代码:

    export default class Animation extends Component {
    constructor(props) {
        super(props);
        this.state = {
            duration:5,
            restartAnimation : false 
        }
    }
    
    
    updateDuration() {
        //before updating duration set resetAnimation to true to remove the svg from dom, then in the callback function set it to false and update duration
         this.setState({
             restartAnimation: true
         }, () => {
             requestAnimationFrame(() => {
                 this.setState({
                     duration: this.state.duration-1,
                     restartAnimation: false
                 })
             })
         })
     }
    
    render() {
        const animationStyle = `countdown ${this.state.duration}s linear infinite forwards`;
    
        //check if resetAnimation is true don't render the svg ( now we removed the svg from dom)
        if(this.state.restartAnimation)
        {
            return (<div></div>);
        }
        //else if resetAnimation is false render the svg but now the new duration and animation will start from the beginning 
        else
        {
            return (
                <svg id={"svg1"}>
                  <circle
                    id="c1"
                    style={{animation: (this.state.restartAnimation ? "" : animationStyle) }}
                    cx="100"
                    cy="100"
                    r="80"
                  >
                  </circle>
                </svg>
            );
        }
    }
    

    }

    【讨论】:

    • 谢谢!我做了与您的建议类似的事情,但您是 100% 正确的。打破动画的唯一方法是删除 SVG 然后将其放回
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-27
    • 2015-09-15
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2021-11-30
    相关资源
    最近更新 更多