【问题标题】:How trigger animation using ref in ReactJS如何在 ReactJS 中使用 ref 触发动画
【发布时间】:2020-03-06 10:50:12
【问题描述】:

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

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

我可能会错过什么?

这里是我的 Reacts 的 sn-ps:

组件

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

感谢任何提示

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

你只需要改变这个

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

收件人:

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

【讨论】:

  • 感谢您的回答,您知道或知道为什么 classList 有效而 className 失败的原因吗?
  • 是的,String.concat 不会更改字符串。它返回一个与前一个字符串连接的新字符串。
  • 并确保删除('animation_trigger}')中的}
猜你喜欢
  • 2018-07-28
  • 2019-10-26
  • 2019-06-16
  • 1970-01-01
  • 2011-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多