React animate transition between components

后端 未结 3 1839
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-08 11:48

I\'d like to animate between two components where the first component fades out and is removed from the DOM before the next component is added to the DOM and fades in. Other

3条回答
  •  鱼传尺愫
    2020-12-08 12:11

    Solved using the componentWillUnmount() lifecycle method.

    http://jsfiddle.net/phepyezx/9/

    Here's the code:

    var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
    
    const Off = React.createClass({
        componentWillUnmount () {
            this.props.handleTransitionEnd();
        },
        render()  {
            return (
                
    OFF
    ) } }); const On = React.createClass({ componentWillUnmount () { this.props.handleTransitionEnd(); }, render() { return (
    ON
    ) } }); var Switch = React.createClass({ getInitialState: function() { return { on: false, transitionEnd: true }; }, toggle: function(e) { this.setState({ on: !this.state.on, transitionEnd: false }); }, handleTransitionEnd() { this.setState({transitionEnd: true}); }, renderOff() { if (! this.state.on && this.state.transitionEnd) { return ( ) } }, renderOn() { if (this.state.on && this.state.transitionEnd) { return ( ) } }, render: function() { return (
    {this.renderOff()} {this.renderOn()}
    ); } }); React.render(, document.getElementById("switch"));

    And the relevant css:

    .switch-enter {
        opacity: 0.01;
    }
    .switch-enter.switch-enter-active {
        opacity: 1.0;
        transition: opacity 500ms ease-in;
    }
    .switch-leave {
        opacity: 1.0;
    }
    .switch-leave.switch-leave-active {
        opacity: 0;
        transition: opacity 500ms ease-out;
    }
    

    You can achieve the same effective result with Jonny Buchanan's answer which uses absolute positioning and a delay instead of componentWillUnmount()

提交回复
热议问题