React - animate mount and unmount of a single component

前端 未结 16 1667
南笙
南笙 2020-12-22 16:34

Something this simple should be easily accomplished, yet I\'m pulling my hair out over how complicated it is.

All I want to do is animate the mounting & unmounti

16条回答
  •  伪装坚强ぢ
    2020-12-22 17:16

    This can be done easily using the CSSTransition component from react-transition-group, which is just like the libraries you mentioned. The trick is you need to wrap the CSSTransition component without a show/hide mechanism like you typically would.i.e. {show && }... Otherwise you are hiding the animation and it won't work. Example:

    ParentComponent.js
    
    import React from 'react';
    import {CSSTransition} from 'react-transition-group';
    
    function ParentComponent({show}) {
    return (
      
        
      
    )}
    
    
    ParentComponent.css
    
    // animate in
    .parentComponent-child-enter {
      opacity: 0;
    }
    .parentComponent-child-enter-active {
      opacity: 1;
      transition: opacity 700ms ease-in;
    }
    // animate out
    .parentComponent-child-exit {
      opacity: 1;
    }
    .parentComponent-child-exit-active {
      opacity: 0;
      transition: opacity 700ms ease-in;
    }
    

提交回复
热议问题