React + Redux:更换组件时如何管理转换

时间:2018-02-11 08:57:27

标签: reactjs css-transitions

我在我的反应应用程序中使用redux来动态地交换进出DOM的组件。我正在尝试做的是发生css转换,淡入淡出并淡出这些组件。

我认为我可以使用CSSTransitionGroup组件,但由于进入和离开组件同时在DOM中(安装新组件而前一个组件仍未卸载),它会混淆布局在这些过渡期间。

我可以通过不显示进入或离开组件来获得淡入或淡出工作,并且在转换过程中我使用css绝对定位将一个放在另一个前面,但两者都有不必要的副作用

如何正确地将一个组件替换为另一个组件并在进入和离开时使用转换?

谢谢!

请参阅下面的组件代码,了解如何使用redux动态替换组件。

组件代码:

import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import Services from '../components/services';
import About from '../components/about';
import Contact from '../components/contact';
import { connect } from 'react-redux';
import { selectDetail } from '../actions/index';
import { CSSTransitionGroup } from 'react-transition-group' 

class Category extends Component {
    constructor(props){
        super(props);
        this.handleDetailSelected = this.handleDetailSelected.bind(this);
    }
    getSelectedCategory(){
        switch (this.props.selectedCategory) {
            case 'about':
                return <About key={ this.props.selectedCategory } handleDetailSelected={this.handleDetailSelected}/>;
            case 'contact':
                return <Contact key={ this.props.selectedCategory } handleDetailSelected={this.handleDetailSelected}/>;
            default:
                return <Services key={ this.props.selectedCategory } handleDetailSelected={this.handleDetailSelected}/>;
        }
    }

    handleDetailSelected(event, detail){
        if(detail){
            this.props.selectDetail(detail);
        }
    }

    render() {
        const category = this.getSelectedCategory();

        return (
            <CSSTransitionGroup
                className="col-xs-12 col-sm-6 content left-content"
                component="div"
                transitionAppear={true}
                transitionAppearTimeout={ 1000 }
                transitionName = "category"
                transitionEnterTimeout={ 1000 }
                transitionLeaveTimeout={ 500 }>
                { category }
            </CSSTransitionGroup>

        );
    }
}

//selectedCategory is set through a navigation component.
function mapStateToProps({ selectedCategory }) {
    return { selectedCategory };
}

function mapDispatchToProps(dispatch) {
    return bindActionCreators({ 
    selectDetail 
    }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(Category);

0 个答案:

没有答案
相关问题