使用react-transition-group v2卸载组件时的基本转换(2018年3月)

arn*_*bro 5 transition reactjs react-transition-group

我设置淡入淡出过渡的代码是最简单的:

import React from 'react';
import { Transition } from 'react-transition-group';
import PropTypes from 'prop-types';

const duration = 250;

const defaultStyle = {
  transition: `opacity ${duration}ms ease-in-out, color ${duration}ms ease-in-out`,
  opacity: 0,
}


const transitionStyles = {
  entering: { opacity: 0 },
  entered: { opacity: 1 },
  exiting: { opacity: 1 },
  exited: { opacity: 0 },
};


export default class Fade extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      in: false,
    };
  }

  componentDidMount() {
    this.setState({ in: true });
  }
  componentWillUnmount() {
    this.setState({ in: false });
  }

  render() {

    return(
      <Transition in={!!this.state.in} timeout={{ enter: 250, exit: 250, }} unmountOnExit={this.props.unmountOnExit || false} >
        {(state) => {
          return (
            <div 
              className={this.props.classes ? this.props.classes : ''} 
              style={{  ...defaultStyle, ...transitionStyles[state],}}>
              {this.props.children}
            </div>
          )
        }}
      </Transition>
    )
  }
}

Fade.propTypes = {
  classes: PropTypes.string,
};
Run Code Online (Sandbox Code Playgroud)

将您的任何组件包裹起来进行尝试。我尝试用它构建一个片段,但我没有成功用 React 构建一个片段,对此感到抱歉。

我的问题:感谢componentDidMount我可以切换组件的状态并使淡入效果完美。然而,我很难将淡出到位:使用并componentWillUnmount不能使它工作。

What is the solution to my problem ? How should I delay the unmounting of the component in order to have the transition going on ?