【问题标题】:Animating height using Framer Motion not working in React使用 Framer Motion 的动画高度在 React 中不起作用
【发布时间】:2023-01-11 01:10:29
【问题描述】:

所以,我一直在尝试为我的 React 项目使用 Framer Motion。当 div 被渲染时,我基本上想将高度从 0 动画化到“自动”。 我试过下面的代码,但高度没有得到动画

<motion.div
  initial={{ height: 0 }}
  animate={{ height: "auto" }}
  transition={{ duration: 0.5 }}
  key={searchQuery?.length}
>

当我用宽度替换高度,动画效果很好,但无法弄清楚为什么高度没有动画。而且我找不到与此相关的任何适当文档。

这是演示的CodeSandbox Link

【问题讨论】:

  • 当您将高度设置为自动而没有成帧器运动时会发生什么?

标签: reactjs animation height framer-motion


【解决方案1】:

Fixed versinn

什么问题?

你的条件渲染逻辑在错误的地方,AnimatePresence 只有当它的直接孩子消失时才有效。

exit道具不见了

keyprop 一定要稳定,不能是字符串的长度

overflow: hidden 必须添加,这样孩子们就看不见了

最终代码:

export default function App() {
  const ref = useRef(null);
  const [isActive, setIsActive] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <div>
        <input
          placeholder={"Enter Keyword"}
          value={searchQuery}
          onChange={(e) => {
            setSearchQuery(e.target.value);
          }}
        />
        <AnimatePresence>
          {searchQuery?.length >= 1 && (
            <motion.div
              style={{ overflow: "hidden" }}
              initial={{ height: 0 }}
              animate={{ height: "auto" }}
              transition={{ duration: 0.5 }}
              exit={{ height: 0 }}
              key={"container"}
            >
              {dataList?.map((listItem) => (
                <div
                  style={{
                    padding: "1rem",
                    color: "#E090EE",
                    borderBottom: "1px solid #E1E1E1",
                  }}
                >
                  {listItem.activity_title}
                </div>
              ))}
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    </div>
  );
}

【讨论】:

    猜你喜欢
    • 2021-03-02
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    相关资源
    最近更新 更多