You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

页面切换时如何去除白色背景?React路由过渡问题求助

问题描述

希望页面实现轮播图式的切换效果,但切换过程中出现的白色背景无法去除。

现有代码

index.js

<React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>

App.js

function App() {
  const location = useLocation();
  return (
    <AnimatePresence>
      <Routes location={location} key={location.pathname}>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </AnimatePresence>
  );
}

Home.js

const Home = () => {
  return (
    <motion.div
      initial={{ y: "100%" }}
      animate={{ y: "0%" }}
      transition={{ bounce: 0, duration: 0.75, ease: "easeOut" }}
      exit={{ opacity: 1 }}
      data-pageName="home"
      className={styles.page}
    >
      <Link to="/about">About</Link>
    </motion.div>
  );
};

About.js

const About = () => {
  return (
    <motion.div
      initial={{ y: "100%" }}
      animate={{ y: "0%" }}
      transition={{ bounce: 0, duration: 0.75, ease: "easeOut" }}
      exit={{ opacity: 1 }}
      data-pageName="about"
      className={styles.page}
    >
      <Link to="/">Home</Link>
    </motion.div>
  );
};
解决方法

1. 修正退出动画逻辑

当前exit={{ opacity: 1 }}会让旧页面始终保持可见,切换时新旧页面叠加,同时容易露出底层白色背景。改成和进入方向相反的滑出动画,实现标准轮播式切换:

// Home.js 和 About.js 统一修改exit属性
exit={{ y: "-100%" }}

2. 消除白色背景来源

  • 给页面容器设置填充视口的背景色,覆盖默认白色:
/* styles.module.css */
.page {
  width: 100vw;
  height: 100vh;
  background-color: #你的目标颜色; /* 替换为需要的背景色,比如#1a1a1a */
  position: fixed;
  top: 0;
  left: 0;
}
  • 给body设置同色系背景,防止动画间隙露出:
/* 全局样式文件 */
body {
  margin: 0;
  padding: 0;
  background-color: #和page一致的颜色;
  overflow: hidden;
}

3. 优化动画过渡时序

若需要更流畅的衔接效果,可调整AnimatePresence的模式,确保旧页面完全退出后新页面再进入:

// App.js中修改AnimatePresence
<AnimatePresence mode="wait">
  {/* 原有Routes内容 */}
</AnimatePresence>

内容的提问来源于stack exchange,提问作者sukrutnrvd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 03:58:29