173°

React动画组件——React-Transitio-group动画实现

安装

项目目录下使用命令行

yarn add react-transition-group
安装组件。在需要使用动画的页面加入以下代码

import { CSSTransition, TransitionGroup } from "react-transition-group";
import "./style.css";
App.js部分
/*
 * @Author: YooHoeh 
 * @Date: 2018-07-14 17:50:52 
 * @Last Modified by: YooHoeh
 * @Last Modified time: 2018-07-15 10:03:58
 * @Description: 
 */

import React, { Component, Fragment } from "react";
import { CSSTransition, TransitionGroup } from "react-transition-group";
import "./style.css";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      list: []
    };
    this.handleAddItem = this.handleAddItem.bind(this);
  }

  render() {
    return (
      <Fragment>
        <button onClick={this.handleAddItem}>Toggle</button>
        <TransitionGroup>
          {this.state.list.map((item, index) => {
            return (
              <CSSTransition
                //将要显示动画的组件外面套上CSSTransition标签
                timeout={1000}
                classNames="fade" //对应CSS里面的'fade-'前缀,可以换成别的,对应的CSS前缀也要换
                unmountOnExit //添加这个属性之后当组件消失时将移除组件的DOM
                onEntered={el => {
                  //这个属性可以给动画播放完毕后的组件执行一次js函数
                  el.style.color = "blue";
                }}
                appear={true} //添加这个属性使组件第一次出现的时候(即页面刚加载时)也使用动画,对应css中的fade-appear和fade-appear-active样式
                key={index}
              >
                <div>{item}</div>
              </CSSTransition>
            );
          })}
        </TransitionGroup>
      </Fragment>
    );
  }
  handleAddItem() {
    this.setState(prevState => {
      return {
        list: [...prevState.list, "item"]
      };
    });
  }
}
export default App;
CSS部分
.fade-enter,
.fade-appear {
  opacity: 0;
}
.fade-enter-active,
.fade-apper-active {
  opacity: 1;
  transition: opacity 1s ease-in;
}
.fade-enter-done {
  opacity: 1;
  color: red;
}
.fade-exit {
  opacity: 1;
}
.fade-exit-active {
  opacity: 0;
  transition: opacity 1s ease-in;
}
.fade-exit-done {
  opacity: 0;
}
效果示意图

本文由【不负好时光】发布于开源中国,原文链接:https://my.oschina.net/shuaihong/blog/3008013

全部评论: 0

    我有话说: