React切换div内容时,如何触发CSS height过渡效果?
React内容切换时实现高度过渡效果的解决方案
问题核心:你当前设置的height过渡不生效,是因为浏览器无法对height: auto的状态变化计算过渡动画——默认情况下容器高度会随内容自动调整,没有明确的数值变化触发过渡。
下面提供两种可行的解决方法:
方法一:用max-height实现简单过渡(适合高度变化范围可控的场景)
这种方法无需JS介入,通过设置max-height的具体值来模拟高度过渡:
修改后的CSS
.venue-details{ position: relative; font-size: 20px; padding-left: 10%; padding-bottom: 30px; padding-right: 10%; max-height: 40px; /* 对应"Click to view"状态的高度 */ overflow: hidden; /* 超出max-height的内容隐藏 */ transition: max-height 1s ease-in-out; } .venue-details.expanded{ max-height: 200px; /* 设置为足够容纳展开后内容的高度 */ }
修改后的React代码
<div className={`venue-details ${venue ? 'expanded' : ''}`}> {venue ? <> <span>Date: To Be Announced... </span><br /> <span>Location: My Location</span><br /> </>: <> <span>Click to view</span> </> } </div>
注意事项:max-height的取值要比展开后内容的实际高度大,避免内容被截断;过渡时间可根据高度差调整,让动画更自然。
方法二:用JS动态计算高度(精准适配任意内容高度)
如果内容高度不确定,可通过JS获取容器的实际高度,强制触发过渡动画:
React代码示例
import { useRef, useEffect, useState } from 'react'; function YourComponent() { const [venue, setVenue] = useState(false); const detailsRef = useRef(null); useEffect(() => { const container = detailsRef.current; if (!container) return; // 先固定当前高度,触发浏览器重绘 container.style.height = `${container.scrollHeight}px`; void container.offsetHeight; // 强制重绘 // 根据状态设置新高度 container.style.height = `${container.scrollHeight}px`; // 过渡结束后重置为auto,保证后续内容变化时高度自适应 const handleTransitionEnd = () => { container.style.height = 'auto'; }; container.addEventListener('transitionend', handleTransitionEnd); return () => container.removeEventListener('transitionend', handleTransitionEnd); }, [venue]); return ( <div ref={detailsRef} className="venue-details" style={{ height: 'auto' }} > {venue ? <> <span>Date: To Be Announced... </span><br /> <span>Location: My Location</span><br /> </>: <> <span>Click to view</span> </> } </div> ); }
修改后的CSS
.venue-details{ position: relative; font-size: 20px; padding-left: 10%; padding-bottom: 30px; padding-right: 10%; transition: height 1s ease-in-out; overflow: hidden; }
这种方法通过scrollHeight获取容器内容的实际高度,先固定当前高度再切换到新高度,让浏览器能识别数值变化从而触发过渡。
内容的提问来源于stack exchange,提问作者Vivek Y V
相关产品推荐
相关产品推荐

