framer-motion 的
AnimatePresence
组件无法按预期工作。
我有以下代码:
import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
export default function App() {
const [a, setA] = useState(true);
return (
<div className="max-w-sm mx-auto">
<button onClick={() => setA((a) => !a)}>Button</button>
<AnimatePresence>
{a ? (
<motion.div
key="a"
initial={{ x: -100, opacity: 0 }}
animate={{ x: 0, opacity: 1 }}
exit={{ x: -100, opacity: 0 }}
transition={{ duration: 2 }}
>
A
</motion.div>
) : (
<motion.div
key="b"
initial={{ x: 100, opacity: 0 }}
animate={{ x: 0, opacity: 1 }}
exit={{ x: 100, opacity: 0 }}
transition={{ duration: 2 }}
>
B
</motion.div>
)}
</AnimatePresence>
</div>
);
}
当我多次单击按钮时,两个组件都会出现,并显示 A 和 B。这是没有意义的,因为应该只出现一个组件。
我无法找到“原因”,但我可以解决它。你能试试这个吗?
import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
export default function Test() {
const [a, setA] = useState(true);
return (
<div className="max-w-sm mx-auto">
<button onClick={() => setA((a) => !a)}>Button</button>
{a && (
<AnimatePresence>
<motion.div
key="a"
initial={{ x: -100, opacity: 0 }}
animate={{ x: 0, opacity: 1 }}
exit={{ x: -100, opacity: 0 }}
transition={{ duration: 2 }}
>
A
</motion.div>
</AnimatePresence>
)}
{!a && (
<AnimatePresence>
<motion.div
key="b"
initial={{ x: 100, opacity: 0 }}
animate={{ x: 0, opacity: 1 }}
exit={{ x: 100, opacity: 0 }}
transition={{ duration: 2 }}
>
B
</motion.div>
</AnimatePresence>
)}
</div>
);
}