基于路由转换和动画仅限某些组件

时间:2016-08-01 16:20:04

标签: reactjs react-router

我有一个React Web应用程序,其中包含导航等选项卡,每个选项卡都有一个单独的路径。通过某种路线,我可以访问某个标签,反之亦然,点击某个标签可以让我到达那条路线。

问题是我想从选项卡进行转换以仅转换和动画化某些组件而不是整个视图 - 只有那些根据路径实际改变的组件。

根据路线,可以仅为某些组件制作动画吗?

1 个答案:

答案 0 :(得分:0)

你的路线应该有一个共同的父母,它将使用react css过渡组为过渡设置动画:

<Route path="/" component={App}> // The parent
    <IndexRoute component={HomePage}/>
    <Route path="page1" component={Page1}/>
    <Route path="page1" component={Page2}/>
    <Route path="page1" component={Page3}/>
    <Route path="page1" component={Page4}/>
</Route>

在路径容器中确定路径是否应该设置动画,并打开/关闭transitionEnter和transitionLeave:

const App = ({ children, location }) => {
  const pathsToAnimate = ['/page1', '/page3']; // a list of routes that should animate
  const shouldAnimate = pathsToAnimate.includes(location.pathname); // check if the current route is among the pathsToAnimate
  return (
    <div>
      <ReactCSSTransitionGroup
        component="div"
        transitionName="example"
        transitionEnter={ shouldAnimate } // animate if shouldAnimate is true
        transitionLeave={ shouldAnimate } // animate if shouldAnimate is true
        transitionEnterTimeout={500}
        transitionLeaveTimeout={500}
      >
        {React.cloneElement(children, {
          key: location.pathname
        })}
      </ReactCSSTransitionGroup>

    </div>
  );
};