javascript - 如何在 ReactJS 中使用 ref 触发动画

标签 javascript reactjs

这是我的演示:https://stackblitz.com/edit/react-pwdkse 注意:使用您的浏览器控制台而不是 Stackblitz 的控制台。似乎浏览器控制台在信息反馈方面更加完整

我会使用 ReactJS ref 的引用来触发动画,而不是在元素范围内更改 className。目前什么都没有发生。

我可能遗漏了什么?

这里是我的 Reacts 片段:

组件

import React, { Component } from 'react';
import { render } from 'react-dom'; 
import './style.module.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React'
    };
     this.animateRef = React.createRef();
  //  this.triggerAnimation = this.triggerAnimation.bind(this);
  }

  componentDidMount(){ 
    // empty scope right now
  }

   triggerAnimation=()=>{ 
      console.log("trigger animateRef animation")

      //   this.animateRef.current.style.animationName="animateElement"
      //  this.animateRef.current.style.animation="1.5s 4.3s 3 alternate forwards"
       this.animateRef.current.className.concat(`animation_trigger`)
        console.log("animateRef: ", this.animateRef)
  }



  render() {

    return (
      <div>

        <p>
          Start editing to see some magic happen :)
        </p>

        <div className="animatedElementStyle" ref={this.animateRef}>
            I am rendered !
        </div>
        <button onClick={this.triggerAnimation}>
          trigger animation
        </button>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

样式表

h1, p {
  font-family: Arial;
}

.animatedElementStyle{ 
    position:absolute;
    top:61%;
    left:10%;
    width:15w;
    height:25vh;
    visibility: hidden; 
    opacity:0;    
}

.animation_trigger{
    animation: animateElement 1.5s 0.5s 3 alternate forwards;
}

@keyframes animateElement{
    from{  
        opacity:0;
        visibility:hidden; 
    }
    100%{
        transform: translate(15%,0);
        opacity:1;
        visibility:visible;
        color:orange;
        font-size:3em;
    }
}

感谢任何提示

最佳答案

你只需要改变这个

this.animateRef.current.className.concat(`animation_trigger`)

收件人:

 this.animateRef.current.classList.add(`animation_trigger`);

关于javascript - 如何在 ReactJS 中使用 ref 触发动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58789687/

相关文章:

javascript - 纯 javascript FormData 上传文件和数据在 PHP 端失败

javascript - 如何在单击时在 React 中打开单个弹出窗口并向其传递 Prop

javascript - 取消拖动或禁用重新排序

ReactJS Material-UI 如何将组件固定在锚定菜单之上

javascript - react - 当 onClick 子项时创建一个事件类

javascript - 如何在 Javascript 中生成文本文件并下载 zip 文件?

javascript - 使用 Handlebars 自定义帮助器方法来隐藏 HTML

javascript - 在 PHP 和 JavaScript 中保存动态添加的行

javascript - 使用 paper.js importSVG() 时,如何更改其路径?

html - Flex-end 和 start 不垂直对齐