參考內容: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
屬性。插件