ReactJS CSS - 如何重新触发@keyframes CSS动画

时间:2018-02-18 17:22:08

标签: javascript css reactjs css-animations

我有一个组件可以切换一些内容和内容的动画,具体取决于它所转换的一面:

import React, { Component } from "react";

class Skills extends Component {
  constructor(props) {
    super(props);

    this.state = {
      shownSkill: 0,
      fallIn: true,
      slideUp: false
    };
  }

  getPreviousSkill = () => {
    const { shownSkill } = this.state;
    const newSkill = shownSkill < 1 ? 3 : shownSkill - 1;
    this.updateShownSkill(newSkill, false);
  };

  getNextSkill = () => {
    const { shownSkill } = this.state;
    const newSkill = shownSkill > 2 ? 0 : shownSkill + 1;
    this.updateShownSkill(newSkill, true);
  };

  updateShownSkill = (skillIndex, fallIn) => {
    this.setState({
      shownSkill: skillIndex,
      fallIn: fallIn,
      slideUp: !fallIn
    });
  };

  getSkillData = () => {
    const { skills } = this.props;
    const { shownSkill } = this.state;
    return skills[shownSkill];
  };

  render() {
    const { name, skill, description } = this.getSkillData();
    const { shownSkill, slideUp } = this.state;
    const { skills } = this.props;
    return (
      <div className="route-container skills">
        <div className="skills-content-container">
          {slideUp ? (
            <div className="skills-right-content slide-up">
              <div className="subtitle">{name}</div>
              {description.map((p, i) => (
                <div className="text" key={i}>
                  {p}
                </div>
              ))}
            </div>
          ) : (
            <div className="skills-right-content
            fall-in">
              <div className="subtitle">{name}</div>
              {description.map((p, i) => (
                <div className="text" key={i}>
                  {p}
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    );
  }
}

export default Skills;

然后我用css:

.fall-in类设置动画
@keyframes fall-in {
  0% {
    margin-top: -600px;
  }
  100% {
    margin-top: 0;
  }
}

.fall-in {
  animation-name: fall-in;
  animation-duration: 0.5s;
  animation-timing-function: linear;
  animation-iteration-count: 1;
}

我希望每次.subtitle.text div的内容发生变化时,此动画都会触发一次,无论动画是否发生变化。

此示例仅在第一次添加css类时触发动画。

1 个答案:

答案 0 :(得分:0)

嘿,也许你想尝试一下我的OSS。

https://github.com/bluebill1049/react-simple-animate

我认为它符合您的要求,或许值得一试?

import Animate from 'react-simple-img';
import React from 'react';

export default ({ready}) => {
   return <Animate startAnimation={ready} startStyle={{
       marginTop: '-600px',
   }} endStyle={{
       marginTop: '0',
   }}>
       <YourComponent />
   </Animate>
};