使用ReactCSSTransitionGroup对路由器4 beta 2进行反应

时间:2017-02-01 13:47:07

标签: react-router react-router-v4

我更喜欢ReactCSSTransitionGroup react-motion。下面的代码会导致组件在路由更改时淡入(显示),但问题是 - 离开组件不会淡出,它会立即离开。

<Switch>
    <FadeRoute exact path="/" component={PageLanding}/>
    <FadeRoute path="/login" component={PageLogin}/>
    <FadeRoute path="/signup" component={PageSignup}/>
    <FadeRoute component={Page404}/>
</Switch>

function FadeRoute({component:Component, ...rest}) {
    return (
        <Route {...rest} children={({location,match}) => (
                <ReactCSSTransitionGroup {...{key:Date.now(), transitionName:'fade', transitionAppear:true, transitionEnter:true, transitionLeave:true, transitionAppearTimeout:300, transitionEnterTimeout:300, transitionLeaveTimeout:300})}>
                    <Component/>
                </ReactCSSTransitionGroup>
        )} />
    );
}
<style>
.fade-enter, .fade-appear { opacity:0; }
.fade-enter.fade-enter-active,
.fade-appear.fade-appear-active { opacity:1; transition: opacity 300ms; }
.fade-leave { opacity:1; }
.fade-leave.fade-leave-active { opacity:0; transition: opacity 300ms; }
</style>

1 个答案:

答案 0 :(得分:13)

<Switch>的工作方式是它只呈现其路径与当前位置匹配的第一个<Route>。这意味着在导航时,导航时会立即卸载现有的<FadeRoute>。它的孩子<CSSTransitionGroup>也是未安装的,因此它没有机会为其子女进行休假过渡。

您要做的是将<Switch>包裹在<CSSTransitionGroup>中。 <Switch>是要转换的组件,因此它应该有key。您还应该将location对象传递给它,这样当<Switch>离开时,它会使用旧的location而不是当前的<CSSTransitionGroup transitionName='fade' transitionEnterTimeout={500} transitionLeaveTimeout={500} > <Switch key={location.pathname} location={location}> <Route path="/red" render={Red} /> <Route path="/green" render={Green} /> <Route path="/blue" render={Blue} /> </Switch> </CSSTransitionGroup> 进行动画制作。

composer