使用 Framer Motion 动画高度在 React 中不起作用

Ari*_*dam 2 height animation reactjs framer-motion

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

<motion.div
  initial={{ height: 0 }}
  animate={{ height: "auto" }}
  transition={{ duration: 0.5 }}
  key={searchQuery?.length}
>
Run Code Online (Sandbox Code Playgroud)

当我用宽度替换高度时,动画工作正常,但无法弄清楚为什么高度没有动画。我无法找到与此相关的任何适当的文档。

这是演示的CodeSandbox 链接。

Kon*_*owy 6

固定版本

什么问题?

您的条件渲染逻辑位于错误的位置,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>
  );
}
Run Code Online (Sandbox Code Playgroud)