React - animate mount and unmount of a single component

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

    Here my 2cents: thanks to @deckele for his solution. My solution is based on his, it's the stateful's component version, fully reusable.

    here my sandbox: https://codesandbox.io/s/302mkm1m.

    here my snippet.js:

    import ReactDOM from "react-dom";
    import React, { Component } from "react";
    import style from  "./styles.css"; 
    
    class Tooltip extends Component {
    
      state = {
        shouldRender: false,
        isMounted: true,
      }
    
      shouldComponentUpdate(nextProps, nextState) {
        if (this.state.shouldRender !== nextState.shouldRender) {
          return true
        }
        else if (this.state.isMounted !== nextState.isMounted) {
          console.log("ismounted!")
          return true
        }
        return false
      }
      displayTooltip = () => {
        var timeoutId;
        if (this.state.isMounted && !this.state.shouldRender) {
          this.setState({ shouldRender: true });
        } else if (!this.state.isMounted && this.state.shouldRender) {
          timeoutId = setTimeout(() => this.setState({ shouldRender: false }), 500);
          () => clearTimeout(timeoutId)
        }
        return;
      }
      mountedStyle = { animation: "inAnimation 500ms ease-in" };
      unmountedStyle = { animation: "outAnimation 510ms ease-in" };
    
      handleToggleClicked = () => {
        console.log("in handleToggleClicked")
        this.setState((currentState) => ({
          isMounted: !currentState.isMounted
        }), this.displayTooltip());
      };
    
      render() {
        var { children } = this.props
        return (
          
    {this.state.shouldRender && (

    {children}

    )}
    ); } } class App extends Component{ render(){ return (
    Here a children
    )}; } const rootElement = document.getElementById("root"); ReactDOM.render(, rootElement);

提交回复
热议问题