React - animate mount and unmount of a single component

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

    Using the knowledge gained from Pranesh's answer, I came up with an alternate solution that's configurable and reusable:

    const AnimatedMount = ({ unmountedStyle, mountedStyle }) => {
      return (Wrapped) => class extends Component {
        constructor(props) {
          super(props);
          this.state = {
            style: unmountedStyle,
          };
        }
    
        componentWillEnter(callback) {
          this.onTransitionEnd = callback;
          setTimeout(() => {
            this.setState({
              style: mountedStyle,
            });
          }, 20);
        }
    
        componentWillLeave(callback) {
          this.onTransitionEnd = callback;
          this.setState({
            style: unmountedStyle,
          });
        }
    
        render() {
          return 
    } } };

    Usage:

    import React, { PureComponent } from 'react';
    
    class Thing extends PureComponent {
      render() {
        return 
    Test!
    } } export default AnimatedMount({ unmountedStyle: { opacity: 0, transform: 'translate3d(-100px, 0, 0)', transition: 'opacity 250ms ease-out, transform 250ms ease-out', }, mountedStyle: { opacity: 1, transform: 'translate3d(0, 0, 0)', transition: 'opacity 1.5s ease-out, transform 1.5s ease-out', }, })(Thing);

    And finally, in another component's render method:

    return 

提交回复
热议问题