1. Introduction
在日常开发中,页面切换时的转场动画是比较基础的一个场景。在react项目当中,我们一般都会选用react-router来管理路由,但是react-router却并没有提供相应的转场动画功能,而是非常生硬的直接替换掉组件。一定程度上来说,体验并不是那么友好。
为了在react中实现动画效果,其实我们有很多的选择,比如:react-transition-group,react-motion,Animated等等。但是,由于react-transition-group给元素添加的enter,enter-active,exit,exit-active这一系列勾子,简直就是为我们的页面入场离场而设计的。基于此,本文选择react-transition-group来实现动画效果。
接下来,本文就将结合两者提供一个实现路由转场动画的思路,权当抛砖引玉~
2. Requirements
我们先明确要完成的转场动画是什么效果。如下图所示:
3. react-router
首先,我们先简要介绍下react-router的基本用法(详细看官网介绍)。
这里我们会用到react-router提供的BrowserRouter,Switch,Route三个组件。
- BrowserRouter:以html5提供的history api形式实现的路由(还有一种hash形式实现的路由)。
- Switch:多个Route组件同时匹配时,默认都会显示,但是被Switch包裹起来的Route组件只会显示第一个被匹配上的路由。
- Route:路由组件,path指定匹配的路由,component指定路由匹配时展示的组件。
// src/App1/index.js
export default class App1 extends React.PureComponent {
render() {
return (
<BrowserRouter>
<Switch>
<Route exact path={'/'} component={HomePage}/>
<Route exact path={'/about'} component={AboutPage}/>
<Route exact path={'/list'} component={ListPage}/>
<Route exact path={'/detail'} component={DetailPage}/>
</Switch>
</BrowserRouter>
);
}
}
如上所示,这是路由关键的实现部分。我们一共创建了首页,关于页,列表页,详情页这四个页面。跳转关系为:
- 首页 ↔ 关于页
- 首页 ↔ 列表页 ↔ 详情页
来看下目前默认的路由切换效果:
4. react-transition-group
从上面的效果图中,我们可以看到react-router在路由切换时完全没有过渡效果,而是直接替换的,显得非常生硬。
正所谓工欲善其事,必先利其器,在介绍实现转场动画之前,我们得先学习如何使用react-transition-group。基于此,接下来就将对其提供的CSSTransition和TransitionGroup这两个组件展开简要介绍。
4.1 CSSTransition
CSSTransition是react-transition-group提供的一个组件,这里简单介绍下其工作原理。
When the in prop is set to true, the child component will first receive the class example-enter, then the example-enter-active will be added in the next tick. CSSTransition forces a reflow between before adding the example-enter-active. This is an important trick because it allows us to transition between example-enter and example-enter-active even though they were added immediately one after another. Most notably, this is what makes it possible for us to animate appearance.
这是来自官网上的一段描述,意思是当CSSTransition的in属性置为true时,CSSTransition首先会给其子组件加上xxx-enter的class,然后在下个tick时马上加上xxx-enter-active

本文探讨如何结合react-router和react-transition-group实现页面转场动画。通过react-router的基础用法和react-transition-group的CSSTransition、TransitionGroup组件,详细介绍了创建页面过渡效果的步骤和技巧,包括动态转场动画的解决方法和优化策略。
最低0.47元/天 解锁文章
664

被折叠的 条评论
为什么被折叠?



