【问题标题】:Exit Animations problem in Route Transitions with framer-motion使用 framer-motion 的 Route Transitions 中的 Exit Animations 问题
【发布时间】:2021-06-23 15:35:14
【问题描述】:

我一直在尝试使用 framer-motion 为路线过渡设置动画,但无法将我的头绕在退出动画上。入口动画可以正常工作。

我希望组件在路线改变时从左侧滑入并向右滑动。

我有

  • 使用 framer-motion 中的 AnimatedPresence 包装 Switch 组件,并使用位置对象并将其路径名作为键。
  • 使用 BrowserRouter 封装所有这些
  • 确保我在每个功能组件的根元素中使用了来自 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>
  );

第二个.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 的键或结构吗?

【问题讨论】:

  • 位置具有关键属性。您是否尝试使用key={props.loc.key} 而不是路径名?
  • 是的,我做到了。不幸的是,结果是一样的。
  • 顺便说一句,我正在尝试解决,因为这对我来说真的很奇怪,但是您的转换是错误的。您将一个对象放在一个对象内部,您可以直接分配转换。 transition:transition 或者你可以使用简写语法{transition}

标签: reactjs react-router-dom framer-motion


【解决方案1】:

您正在使用&lt;a&gt; 标签进行路由,您需要使用react-router-dom 中的Link。然后就可以了。

【讨论】:

  • 非常感谢您解决了这个令人头疼的问题!从这里开始阅读文档时,我会更加小心。非常感谢!
猜你喜欢
  • 2021-09-14
  • 1970-01-01
  • 2022-11-21
  • 1970-01-01
  • 2023-01-11
  • 2021-09-10
  • 2022-09-28
  • 2020-12-18
  • 1970-01-01
相关资源
最近更新 更多