我之前問過關於如何實現頁面滑動動畫的問題:page sliding animation with React Router v4 and react-transition-group v2。動態頁面滑動動畫與React路由器v4和react-transition-group v2
之後,我遇到了一個更困難的問題。
function getPathDepth(location) {
let pathArr = (location || {}).pathname.split('/');
pathArr = pathArr.filter(n => n !== '');
return pathArr.length;
}
class Routers extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
prevDepth: getPathDepth(props.location)
};
}
componentWillReceiveProps() {
this.setState({ prevDepth: getPathDepth(this.props.location) });
}
render() {
return (
<Route render={({ location }) => {
return (
<TransitionGroup>
<CSSTransition
key={location.key}
timeout={500}
classNames={ getPathDepth(location) - this.state.prevDepth > 0 ? 'pageSliderLeft' : 'pageSliderRight' }
classNames={classNames}
mountOnEnter={true}
unmountOnExit={true}
>
<Switch location={location}>
<Route path="/" exact component={ Index } />
<Route path="/comments" component={ Comments } />
<Route path="/opinions" component={ Opinions } />
<Route path="/games/lol" component={ LOL } />
<Route path="/games/dota" component={ DotA } />
<Route path="/games" component={ Games } />
</Switch>
</CSSTransition>
</TransitionGroup>
);
}} />
)
}
}
const WrapRouters = withRouter(Routers);
export default function RouterMap() {
return (
<BrowserRouter>
<WrapRouters />
</BrowserRouter>
);
}
的CSS:
.pageSliderRight-enter {
transform: translate3d(-100%, 0, 0);
}
.pageSliderRight-enter.pageSliderRight-enter-active {
transform: translate3d(0, 0, 0);
transition: all 600ms;
}
.pageSliderRight-exit {
transform: translate3d(0, 0, 0);
}
.pageSliderRight-exit.pageSliderRight-exit-active {
transform: translate3d(-100%, 0, 0);
transition: all 600ms;
}
.pageSliderLeft-enter {
transform: translate3d(100%, 0, 0);
}
.pageSliderLeft-enter.pageSliderLeft-enter-active {
transform: translate3d(0, 0, 0);
transition: all 600ms;
}
.pageSliderLeft-exit {
transform: translate3d(0, 0, 0);
}
.pageSliderLeft-exit.pageSliderLeft-exit-active {
transform: translate3d(100%, 0, 0);
transition: all 600ms;
}
動畫:
如果僅僅從 '/' 到 '/遊戲',然後滑動從 '/遊戲' 回'/', 一切安好。但隨着更多的路線,它變得複雜。
從'/'到'/ games'時,遊戲的退出動畫被指定,不可更改。但顯然,它應該是動態的。
- '/' - > '/遊戲' & & '/遊戲' - > '/',退出動畫應該是 '滑向右'
- '/' - >' /遊戲& &‘/遊戲’ - >‘/遊戲/笑’,退出動畫應該是‘滑動至左側’
更一般地,越來越深路由時,滑動動畫應該是'滑向左邊「。否則,動畫應該是'向右滑動'。
如何動態設置動畫?
我認爲這個問題是不具有正確的狀態退出的元素,因爲過渡可能克隆元素退出前。我必須研究它,但可能必須使用transitiongroup childFactory。 – MatijaG