将 React SwitchTransition 与挂载和卸载组件一起使用

时间:2021-07-22 06:01:02

标签: reactjs react-hooks react-router-dom react-transition-group

安装带有路由路径的组件时,我想触发 CSSTransition。我的目标是让即将卸载的组件持续足够长的时间,以便安装组件完全过渡。

模拟等效将两张卡片相互滑动,然后才移除下面被遮挡/隐藏的卡片。

import {
  Switch,
  BrowserRouter,
  Route,
  Redirect,
  useLocation,
} from 'react-router-dom';
import {
  CSSTransition,
  TransitionGroup,
  SwitchTransition,
} from 'react-transition-group';

import NavBar from './jsx/NavBar';
import Home from './jsx/Home';
import SomePage from './jsx/SomePage';

function App() {
  let location = useLocation();
  return (
    <div className='App'>
      <NavBar />
      <TransitionGroup>
        <SwitchTransition mode='in-out'>
          <CSSTransition
            key={location.key}
            classNames='slide'
            timeout={{
              enter: 0,
              exit: 500,
            }}
          >
            <Switch>
              <Route path='/' exact>
                <Redirect to='/home' />
              </Route>
              <Route path='/home' component={Home} exact />
              <Route path='/page' component={SomePage} />
            </Switch>
          </CSSTransition>
        </SwitchTransition>
      </TransitionGroup>
    </div>
  );
}

.navbar {
  width: 100%;
  position: fixed;
  top: 0;
  z-index: 99;
}

.home {
  height: 100vh;


.some-page {
  height: 100vh;
  width: 100%;
  transform: translateY(100vh);
  background-color: red;
}

.animate {
  position: absolute;
  z-index: 1;
  top: 0;
  transition: transform 0.75s ease-in;
  overflow: hidden;
}

.slide-enter-done {
  transform: translateY(0vh);

0 个答案:

没有答案