寫這個只是更好的梳理下我實現過程當中遇到的奇奇怪怪的問題,react
由於着實浪費了我很多時間…確定有很多也碰到過其中的問題bash
但願對小夥伴有所幫助。react-router
spread
的效果,其實就是結合放大和旋轉以及透明度的特性fade
styled-components@3.4.2
: 寫樣式的react-transition-group@2.4.0
: 路由過渡的,react
官方的react-router-dom@4.3.1
: react
自家路由react@16.4.2
就是再次進入路由切換的時候,以前的元素尚未消失,而新的組件渲染了,同時出現app
position:absolute
來負責渲染區域便可position:relative
, 否則會一直往上找相對位置,實在找不到會相對窗口shouldComponentUpdate
來判斷URL而後阻止渲染,發現不可行location.key
是隨機性的,因此組件每次都會從新渲染Link
組件,直接用事件綁定(history.push
來跳轉),完美CSSTransition
的特性,由於location.key
是隨機性的,不一樣值都會走一遍;Math.random()
默認返回0~1隨機浮點數,這裏只有兩個就不用成個數了// 路由跳轉
gotoUrl = itemurl => {
// 拿到路由相關的信息
const { history, location } = this.props;
// 判斷咱們傳入的靜態路由表的路徑是否和路由信息匹配
// 不匹配則容許跳轉,反之打斷函數
if (location.pathname === itemurl) {
return;
} else {
history.push(itemurl);
}
};
複製代碼
import React, { Component } from 'react';
import { TransitionGroup, CSSTransition } from 'react-transition-group';
import { Route, Redirect, withRouter, Switch } from 'react-router-dom';
import styled from 'styled-components';
import { observer, inject } from 'mobx-react';
import asyncComponent from 'components/asyncComponent/asyncComponent';
const RouterAnimationClass = styled.div`
.fade-appear,
.fade-enter {
opacity: 0;
}
.fade-appear-active,
.fade-enter-active {
transition: opacity 0.3s linear;
opacity: 1;
}
.fade-exit {
transition: opacity 0.2s linear;
opacity: 1;
}
.fade-exit-active {
opacity: 0;
}
.spread-appear,
.spread-enter {
opacity: 0.5;
transform: scale(0) rotate(30deg);
}
.spread-appear-active,
.spread-enter-active {
opacity: 1;
transform: scale(1) rotate(0);
transition: transform 0.3s ease-in-out;
}
.spread-exit {
transition: transform 0.2s ease-in-out;
transform: scale(1.2) rotate(-30deg);
}
.spread-exit-active {
transform: scale(0) rotate(0);
}
.page-content {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
width: 100%;
}
`;
const Monitor = asyncComponent(() => import('pages/DashBoard/Monitor'));
const Analyze = asyncComponent(() => import('pages/DashBoard/Analyze'));
import ErrorPage from 'pages/Error/Error'; // 報錯頁面
@inject('auth')
@withRouter
@observer
class Container extends Component {
constructor(props) {
super(props);
}
render() {
const { location } = this.props;
return (
<RouterAnimationClass>
<TransitionGroup>
<CSSTransition
key={location.key}
classNames={
['fade', 'spread'][parseInt(Math.random(), 10)]
}
timeout={1000}>
<div className="page-content">
<Switch location={location}>
<Route
path="/dashboard/monitor"
exact
component={Monitor}
/>
<Route
path="/dashboard/analyze"
exact
component={Analyze}
/>
<Redirect
exact
from="/"
to="/dashboard/monitor"
/>
<Route component={ErrorPage} />
</Switch>
</div>
</CSSTransition>
</TransitionGroup>
</RouterAnimationClass>
);
}
}
export default Container;
複製代碼