React - animate mount and unmount of a single component

前端 未结 16 1757
南笙
南笙 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:17

    I think using Transition from react-transition-group is probably the easiest way to track mounting/unmounting. It is incredibly flexible. I'm using some classes to show how easy it is to use but you can definitely hook up your own JS animations utilizing addEndListener prop - which I've had a lot of luck using GSAP with as well.

    Sandbox: https://codesandbox.io/s/k9xl9mkx2o

    And here's my code.

    import React, { useState } from "react";
    import ReactDOM from "react-dom";
    import { Transition } from "react-transition-group";
    import styled from "styled-components";
    
    const H1 = styled.h1`
      transition: 0.2s;
      /* Hidden init state */
      opacity: 0;
      transform: translateY(-10px);
      &.enter,
      &.entered {
        /* Animate in state */
        opacity: 1;
        transform: translateY(0px);
      }
      &.exit,
      &.exited {
        /* Animate out state */
        opacity: 0;
        transform: translateY(-10px);
      }
    `;
    
    const App = () => {
      const [show, changeShow] = useState(false);
      const onClick = () => {
        changeShow(prev => {
          return !prev;
        });
      };
      return (
        
    {state => { let className = state; return

    Animate me

    ; }}
    ); }; const rootElement = document.getElementById("root"); ReactDOM.render(, rootElement);

提交回复
热议问题