参考内容:react
使用的插件是react-transition-group
。先简单介绍一下动画插件的使用方式。web
CSSTransition
这个组件有两个比较主要的属性:key
和in
。api
in:Boolean
属性其实能够理解为是否显示当前内容节点。true
则显示,false
则不显示。数组
key:String
这个属性是配合TransitionGroup
组件来使用的。在通常的列表组件中(列如 todolist),能够经过key
来判断列表中的子节点须要被插入仍是移除,而后触发动画。浏览器
这个组件有一个很重要的属性:location
。同时这个属性也是路由切换动画的关键所在。Switch
组件的子组件(通常是 Route 和 Redirect)会根据当前浏览器的location
做为匹配依据来进行路由匹配。可是若是Switch
组件定义了location
属性,其中的子组件就会以定义的location
做为匹配依据。react-router
import React, { Component } from 'react' import { TransitionGroup, CSSTransition } from 'react-transition-group' import { Switch, Route, withRouter } from 'react-router-dom' @withRouter class Routes extends Component { render() { const location = this.props.location return ( <TransitionGroup> <CSSTransition key={location.key} timeout={1000} classNames="fade"> <Switch location={location}> <Route path="/route-1" component={Route1} /> <Route path="/route-2" component={Route2} /> </Switch> </CSSTransition> </TransitionGroup> ) } } export default Routes
先肯定需求:当切换路由的时候,旧的路由内容在必定时间内过渡消失,新的路由内容过渡显示。
在这个须要里面有两个重要的部分:dom
刚刚提到的CSSTransition
的key
属性能够决定该节点是否须要显示。
而Router
中的location
属性会在路由发生变化的时候,进行更新,而location
里面的key
则能够做为CSSTransition
的key
。动画
关于 history 对象,能够理解为一个数组,当页面的 location 发生变化时,或者刷新页面,history 就会push
一个新的历史信息。在这个历史信息里面,有一个key
属性,用来区分不一样的历史记录(跳转新页面或者是刷新页面)
当路由切换的时候,location
对象就会改变,新的key
会使得页面从新渲染时出现两个CSSTransition
(新旧节点)。this
若是只是配置key
属性,会发现旧的节点会去匹配新的路由内容。这是由于Route
组件默认根据当前location
进行匹配。为了让旧节点中的Route
根据旧的location
进行匹配,就须要设置Switch
的location
属性。插件