React-transition-group 之单组件过渡动画

概述:

在react开发的过程中,有时候需要给特定的页面或组件单独加上过渡动画,特别是给某个路由页面增加动画的时候,需要在页面组件中添加比较多的操作,并且每次需要添加动画的时候都要写一遍,实在比较麻烦,同时也增加了代码量和可读性,出于这个理由,把单组件过渡进行封装显的非常必要,在这里,采用了HOC的形式

需求:

  1. 单个组件进入和离开时需要动画
  2. HOC应该给包裹过的组件添加一个prop 用于退出组件

废话不多说,直接上代码

先看使用方法

import React, { Component } from 'react';
import { withSingleTransition } from "../../../components/withTransition/with-single-transition/with-single-transition";

@withSingleTransition('page', 300)
class page extends Component {

  goBack = () => {
    this.props.goBack().then(() => do something)
    //  注意 如果过渡的是路由,需要在then里显式的调用push 或 goBack方法,否则路由不会卸载
    // this.props.goBack().then(() => this.props.history.goBack())
  };
  .....
  .....
}

import React from 'react';
import {CSSTransition} from 'react-transition-group';

export function withSingleTransition(classNames = 'page', timeout = 500) {
  return function(WrappedComponent) {
    return class Comp extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          in: true
        };
        this.goBack = this.goBack.bind(this);
      }
      goBack() {
        const that = this;
        return new Promise((resolve) => {
          that.setState({in: false});
          setTimeout(() => {
            resolve()
          }, timeout)
        });
      }
      render() {
        return (
          <CSSTransition timeout={timeout}
                         in={this.state.in}
                         classNames={classNames}
                         appear={true}
                         unmountOnExit={true}>
            <WrappedComponent {...this.props} goBack={this.goBack}/>
          </CSSTransition>
        )
      }
    }
  }
}

在这里,因为实在组件内部使用过渡,所以过渡组件挂载的时候需要立即调用,设置appear={true}

所以最后,需要添加的样式为
xxx-appear、xxx-appear-active、 xxx-enter-done、xxx-exit、xxx-exit-active、xxx-exit-done

猜你喜欢

转载自blog.csdn.net/wang913003120/article/details/85541438