【发布时间】:2021-04-05 16:37:16
【问题描述】:
我正在尝试将TransitionGroup 和CSSTransition 与react-router-dom 一起使用来创建页面之间的平滑过渡。出于调试目的,我将淡入淡出转换时间设置为 5 秒。
这是我的App 组件:
function Inner(): React.ReactElement {
const location = useLocation()
const currentKey = location.pathname.split("/")[1] || "/"
return (
<TransitionGroup component="div" className="main">
<CSSTransition key={currentKey} timeout={5000} classNames="fade">
<Switch location={location}>
<Route path="/guild" component={Guild} />
<Route exact path="/" component={Home} />
</Switch>
</CSSTransition>
</TransitionGroup>
)
}
function App(): React.ReactElement {
return (
<Switch>
<Route path="*">
<Inner />
</Route>
</Switch>
)
}
它正确嵌套在 React 以及我的 Redux Provider 和 react-router-dom 的 BrowserRouter 在我的 index.tsx 文件中:
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
</React.StrictMode>,
document.getElementById("root")
)
以及用于淡入淡出的 CSS:
.fade-enter {
opacity: 0 !important;
z-index: 100 !important;
}
.fade-enter.fade-enter-active {
opacity: 1 !important;
transition: opacity 5000ms ease-in !important;
}
.fade-exit {
opacity: 1 !important;
}
.fade-exit.fade-exit-active {
opacity: 0 !important;
transition: opacity 5000ms ease-in !important;
}
出于演示目的,我将Home 和Guild 组件设置为相互链接,这样我就可以来回切换。应该发生的是,它们应该在过渡期间逐渐消失。
相反,新组件立即垂直显示在另一个不透明度为 0 的组件上方,将旧组件垂直向下推。然后过渡开始发生,顶部的新组件逐渐淡入,而下方的旧组件逐渐淡出。转换完成后,旧组件将被卸载。
我已经尝试了所有我能想到的方法来防止新出现的组件压低旧组件。它们应该直接层叠在一起,以给人一种组件淡入另一个组件的印象。我在网上找到的所有示例似乎都是这样做的。据我所知,我做的事情和他们完全一样。
这是页面加载后的样子:
这是点击公会后的样子:
注意公会组件(现在它只是一个显示“即将推出...”的页面)如何弹出到主页组件上方。
几秒钟后:
看看顶部如何随着底部的淡出而淡入。如果它们彼此重叠而不是垂直堆叠,这将是完美的。
那么最后,动画结束后:
【问题讨论】:
-
我可以建议将所有这些都放入沙箱吗?这将使我们更容易排除故障。
-
你必须让每个页面的父或根是
position: absolute;可能是top: 0; left: 0;但这取决于你。
标签: css reactjs typescript css-transitions react-router-dom