一次react-router + react-transition-group实现转场动画的探索

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

原文地址

1. Introduction

在日常开发中,页面切换时的转场动画是比较基础的一个场景。在react项目当中,我们一般都会选用react-router来管理路由,但是react-router却并没有提供相应的转场动画功能,而是非常生硬的直接替换掉组件。一定程度上来说,体验并不是那么友好。

为了在react中实现动画效果,其实我们有很多的选择,比如:react-transition-groupreact-motionAnimated等等。但是,由于react-transition-group给元素添加的enter,enter-active,exit,exit-active这一系列勾子,简直就是为我们的页面入场离场而设计的。基于此,本文选择react-transition-group来实现动画效果。

接下来,本文就将结合两者提供一个实现路由转场动画的思路,权当抛砖引玉~

2. Requirements

我们先明确要完成的转场动画是什么效果。如下图所示:

3. react-router

首先,我们先简要介绍下react-router的基本用法(详细看官网介绍)。

这里我们会用到react-router提供的BrowserRouterSwitchRoute三个组件。

  • 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>
    );
  }
}

如上所示,这是路由关键的实现部分。我们一共创建了首页关于页列表页详情页这四个页面。跳转关系为:

  1. 首页 ↔ 关于页
  2. 首页 ↔ 列表页 ↔ 详情页

来看下目前默认的路由切换效果:

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学而鸠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值