使用React Router V4时如何防止组件立即卸载

时间:2019-07-25 14:14:10

标签: reactjs react-router react-router-v4 react-transition-group

我正在使用react-transition-group的标签使用react-router-v4在路线之间创建动画。我正在使用标签根据状态变化在代码中的路由之间进行切换。我遇到的问题是,当触发a时,在给出口动画时间播放之前,该组件会立即卸载。新路线的动画效果正确。

我试图通过遵循React Transition Group网站上的以下页面来解决此问题:https://reactcommunity.org/react-transition-group/with-react-router

它承认我要立即卸下组件时遇到的问题,但是我的解决方案似乎无法正常工作。

const routes = [
  { path: '/', name: 'Dashboard', Component: Dashboard },
  { path: '/detailedview', name: 'DetailedView', Component: DetailedView },
  { path: '/dashboardloop', name: 'DashboardLoop', Component: DashboardLoop },
]

function Example() {
  return (
    <Router>
      <>
        <Container className="container">
          {routes.map(({ path, Component }) => (
            <Route key={path} exact path={path}>
              {({ match }) => (
                <CSSTransition
                  in={match != null}
                  timeout={500}
                  classNames="page"
                  unmountOnExit
                >
                  <div className="page">
                    <Component />
                  </div>
                </CSSTransition>
              )}
            </Route>
          ))}
        </Container>
      </>
    </Router>
  )
}

ReactDOM.render((
  <Example/>
), document.getElementById('root'));

任何帮助将不胜感激!谢谢

1 个答案:

答案 0 :(得分:0)

迟到聚会时,您可能已经自己解决了这个问题,但是为了记录供人们搜索该问题:请检查CSS。

CSSTransition依赖于四个CSS类(如文档中所述):

/* Starting style of enter animation, i.e when element is still invisible */
.page-transition-enter{
}

/* How the element will look on the page + transition (which does the animation) goes here*/
.page-transition-enter-active{
}

/* Start of exit animation, usually how the element looks on the page */
.page-transition-exit{
}

/*The end-style of exit-animation + transition */
.page-transition-exit-active{
}

React Transition Group文档(http://reactcommunity.org/react-transition-group/css-transition)中的一个简单过渡示例:

.page-enter {
  opacity: 0;
}
.page-enter-active {
  opacity: 1;
  transition: opacity 200ms;
}
.page-exit {
  opacity: 1;
}
.page-exit-active {
  opacity: 0;
  transition: opacity 200ms;
}

由于您的元素在没有动画的情况下会卸载,但在进入时会设置动画,因此看来您很可能在最后两个类中缺少了某些内容。或完全缺少其中一个或两个类别。