React路由動(dòng)畫切換實(shí)現(xiàn)過程詳解
1.下載
cnpm install react-transition-group --save
2.配置
在路由配置文件/src/App.js文件下中導(dǎo)入動(dòng)畫組件
引入
import {TransitionGroup, CSSTransition} from 'react-transition-group'
在路由組件模板中,用動(dòng)畫組件包裹路由組件
<TransitionGroup> <CSSTransition timeout={3000} classNames="dg" unmountOnExit key={props.location.pathname}> <Switch location={props.location}> <Route path="/" exact component={Login}/> <Route path="/child1" exact component={Home}/> <Route path="/child2" exact component={My}/> </Switch> </CSSTransition> </TransitionGroup>
使用動(dòng)畫的寫法 CSSTransition 需要設(shè)置三個(gè)屬性:
- in: 控制子元素顯示隱藏的條件,一般是bool值或表達(dá)式
- timeout: 入場(chǎng)或出場(chǎng)動(dòng)畫的時(shí)間,單位默認(rèn)毫秒
- className: 入場(chǎng)或出場(chǎng)class屬性名前綴
注意:CSSTransition組件的key屬性值要保證唯一性,所以用location.pathname
Switch組件要設(shè)置location屬性為路由信息的props.location,保證路由跳轉(zhuǎn)組件的key和CSSTransition的key一致
如果路由中沒有l(wèi)ocation.pathname,需要使用withRouter導(dǎo)入
import { withRouter } from 'react-router-dom' export default withRouter(App);
3.引入css
在組件中寫出路由切換動(dòng)畫的過程
/* 入場(chǎng)動(dòng)畫過程 */ .dg-enter{ transform: translateX(200px) } .dg-enter-active{ transition: 2s; transform: translateX(0px) } .dg-enter-done{ transform: translateX(0px) } /* 出場(chǎng)動(dòng)畫過程 */ .dg-exit{ transform: translateX(0px) } .dg-exit-active{ transition: 2s; transform: translateX(200px) } .dg-exit-done{ transform: translateX(200px) }
引入css文件
import './app.css'
這樣一個(gè)簡單的React路由動(dòng)畫切換就實(shí)現(xiàn)了
4.結(jié)合animate庫
我們可以自己定義classNames,然后使用css3設(shè)置動(dòng)畫,也可以結(jié)合animate庫設(shè)置他的動(dòng)畫效果
下載
npm install animate.css --save
引入
import 'animate.css';
//自定義的類名(定義動(dòng)畫效果,進(jìn)場(chǎng)前,進(jìn)場(chǎng)后直到結(jié)束,結(jié)束前,結(jié)束后) classNames={{ enter: "animate__animated", enterActive: "animate__fadeIn", exit: "animate__animated", exitActive: "animate__fadeOut", }}
具體的我們可以進(jìn)行參考animate官網(wǎng)網(wǎng)址:Animate.css | A cross-browser library of CSS animations.
到此這篇關(guān)于React路由動(dòng)畫切換實(shí)現(xiàn)過程詳解的文章就介紹到這了,更多相關(guān)React路由動(dòng)畫切換內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決React報(bào)錯(cuò)Expected an assignment or funct
這篇文章主要為大家介紹了React報(bào)錯(cuò)Expected an assignment or function call and instead saw an expression解決方案詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12React實(shí)現(xiàn)類似淘寶tab居中切換效果的示例代碼
這篇文章主要介紹了React實(shí)現(xiàn)類似淘寶tab居中切換效果,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06