具有 framer-motion 的 Route Transitions 中的退出动画问题

Exit Animations problem in Route Transitions with framer-motion

我一直在尝试使用 framer-motion 为路线转换制作动画,但无法围绕退出动画进行处理。入口动画正常工作。

我想让组件从左边滑入,当路由变化时向右滑入

我已经

Codesandbox

App.js

function App() {
  const location = useLocation();
  return (
    <div className="App">
      <AnimateTrans loc={location} />
    </div>
  );
}

AnimateTrans.jsx

export default function (props) {
  return (
    <AnimatePresence exitBeforeEnter>
      <Switch location={props.loc} key={props.loc.pathname}>
        <Route exact path="/">
          <First />
        </Route>
        <Route exact path="/sec">
          <Second />
        </Route>
      </Switch>
    </AnimatePresence>
  );
}

First.jsx

    const transition = {
    duration: 1,
    type: "spring"
  };

  const transVariants = {
    init: { scale: 0.3, opacity: 1, x: -400, transition: { transition } },
    anim: { scale: 1, opacity: 1, x: 0, transition: { transition } },
    exit: { scale: 0.4, opacity: 0, x: 400, transition: { transition } }
  };
  return (
    <motion.div
      variants={transVariants}
      initial="init"
      animate="anim"
      exit="exit"
      className="container"
    >
      <div className="content">
        <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ1a79XgKvvi2VyAu54LI21MbKrfSlZTL9iPA&usqp=CAU" />
      </div>
      <div className="oth"></div>
      <a href="/sec">d</a>
    </motion.div>
  );

Second.jsx

const transition = {
    duration: 1,
    type: "spring"
  };

  const transVariants = {
    initial: { scale: 0.3, opacity: 1, x: -400, transition: { transition } },
    animate: { scale: 1, opacity: 1, x: 0, transition: { transition } },
    exit1: { scale: 0.4, opacity: 0, x: 400, transition: { transition } }
  };
  return (
    <motion.div
      variants={transVariants}
      initial="initial"
      animate="animate"
      exit="exit1"
      className="container"
    >
      <div className="content">
        <img src="https://fashioneditorials.com/wp-content/uploads/2017/10/i-D-Japan-Chanel-Haute-Couture-With-Nana-Komatsu-Angelo-Pennetta-1.jpg" />
      </div>
      <div className="oth"></div>
      <a href="/">d</a>
    </motion.div>
  );
}

我的位置对象在这里有问题吗?我应该以不同的方式更改密钥或结构 App.js 吗?

您正在使用 <a> 标签进行路由,您需要使用 Link from react-router-dom。然后就可以了。