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

React中用HOC与Framer Motion实现页面过渡时的导出导入问题

问题解决:React + Framer Motion 页面过渡的HOC导入导出错误及动画实现

错误原因分析

  1. 命名导入报错:PageWrapper采用的是默认导出,并非命名导出,因此不能使用import { PageWrapper }的命名导入语法,必须用默认导入方式。
  2. 默认导入后组件无效:PageWrapper函数内部未返回定义好的HOC组件,调用PageWrapper(Home)会返回undefined,React无法渲染undefined类型的元素。

修复步骤

1. 修复HOC组件代码

在PageWrapper函数中返回定义的HOC组件,同时调整exit属性让退出过渡生效:

import { motion } from "framer-motion";

const PageWrapper = (Page) => {
  // 必须返回该HOC组件
  return function HOC() {
    return (
      <motion.div
        initial={{ y: "100%" }}
        animate={{ y: "0%" }}
        transition={{ duration: 1, ease: "easeOut" }}
        exit={{ y: "100%", opacity: 0 }} // 调整为有实际过渡效果的退出配置
      >
        <Page />
      </motion.div>
    );
  };
};

export default PageWrapper;

2. 确认页面导入导出方式

Home页面的导入导出逻辑是正确的,保持即可:

import PageWrapper from "../HOC/PageTransitionWrapper";

function Home() {
  return (
      <>MY CODE</>
  );
}

export default PageWrapper(Home);

3. 验证RootLayout配置

确保location通过useLocation()正确获取,AnimatePresence配置保持现有逻辑:

import { useLocation } from "react-router-dom";
import { AnimatePresence } from "framer-motion";
import { Box } from "@mui/material";
import Navbar from "./Navbar";

export default function RootLayout() {
  const location = useLocation();
  
  return (
    <Box>
      <Navbar />
      <AnimatePresence key={location.pathname} initial={false}>
        <Outlet />
      </AnimatePresence>
    </Box>
  );
}

额外注意事项

  • 所有需要过渡效果的页面都必须通过PageWrapper包裹,这样AnimatePresence才能检测组件挂载/卸载状态以触发动画。
  • AnimatePresence的key属性必须唯一,使用location.pathname可以保证页面切换时的唯一性,确保退出动画正常触发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 05:05:18