framer-motion 的 AnimatePresence 无法按预期工作

问题描述 投票:0回答:1

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。这是没有意义的,因为应该只出现一个组件。

javascript reactjs animation framer-motion
1个回答
0
投票

我无法找到“原因”,但我可以解决它。你能试试这个吗?

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>
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.