React中使用Framer Motion实现高度动画失效问题
Framer Motion 高度从0到auto动画失效的解决办法
Framer Motion 没办法直接在数值(比如0)和关键字auto之间做过渡动画——因为auto是依赖内容的动态值,动画引擎无法提前计算出中间过渡的具体高度帧,这就是你看到高度动画失效的核心原因。而width动画能生效,大概率是因为你的场景中width:auto能被解析为某个固定父容器的宽度数值,动画引擎可以完成过渡计算。
下面给你两种实用的解决方法:
方法一:使用Framer Motion的layout属性
layout属性可以自动追踪元素尺寸变化并生成过渡动画,不用手动指定height值,是最简便的方案:
<motion.div initial={{ height: 0, opacity: 0 }} animate={{ height: "auto", opacity: 1 }} layout transition={{ duration: 0.5 }} key={searchQuery?.length} style={{ overflow: "hidden" }} > {/* 你的内容 */} </motion.div>
注意要加上overflow: hidden,避免初始height为0时内容溢出显示。
方法二:手动计算内容高度
通过useRef获取元素,提前计算内容的实际高度(scrollHeight),用这个具体数值作为动画目标:
import { useState, useRef, useEffect } from 'react'; import { motion } from 'framer-motion'; function SearchResults() { const contentRef = useRef(null); const [contentHeight, setContentHeight] = useState(0); // 监听搜索词变化,重新计算内容高度 useEffect(() => { if (contentRef.current) { setContentHeight(contentRef.current.scrollHeight); } }, [searchQuery]); return ( <motion.div initial={{ height: 0 }} animate={{ height: contentHeight }} transition={{ duration: 0.5 }} key={searchQuery?.length} style={{ overflow: "hidden" }} ref={contentRef} > {/* 你的搜索结果内容 */} </motion.div> ); }
内容的提问来源于stack exchange,提问作者Arindam
相关产品推荐
相关产品推荐

