React实现未知高度div滑入滑出动画关闭延迟问题如何解决
问题根因
你遇到的延迟本质是max-height过渡的特性导致的:过渡动画的时长是按你设置的max-height差值计算的,你把打开状态的max-height设为了window.innerHeight,如果实际内容高度远小于这个值,关闭动画的前半段会在不可见的高度区间变化,视觉上就会出现明显延迟。
解决方案
方案1:动态计算内容高度设置max-height
通过ref获取DOM元素的实际内容高度scrollHeight,动态给maxHeight赋值,完全避免多余的高度区间:
- 调整自定义CSS,补充必填的
overflow属性:
.transition-height{ transition: max-height 0.5s ease-in-out; overflow: hidden; /* 必须添加,否则内容超出时不会隐藏,过渡效果失效 */ }
- React组件实现逻辑:
import { useRef, useState, useEffect } from 'react'; function SlidingDiv() { const [isOpen, setIsOpen] = useState(false); const contentRef = useRef(null); useEffect(() => { if (isOpen) { // 打开时设置为实际内容高度 contentRef.current.style.maxHeight = `${contentRef.current.scrollHeight}px`; } else { // 关闭时设置为0 contentRef.current.style.maxHeight = '0px'; } }, [isOpen]); return ( <div> <button onClick={() => setIsOpen(!isOpen)}>切换显示</button> <div ref={contentRef} className="transition-height"> {/* 你的动态内容 */} </div> </div> ); }
如果后续内容会动态更新,额外监听内容变化重新赋值maxHeight即可。
方案2:直接使用react-bootstrap内置Collapse组件
你当前使用的react-bootstrap 1.6.1本身已经封装了成熟的折叠动画组件,不需要自定义过渡逻辑,自动适配动态内容高度,无延迟问题:
import { useState } from 'react'; import { Button, Collapse } from 'react-bootstrap'; function SlidingDiv() { const [isOpen, setIsOpen] = useState(false); return ( <div> <Button onClick={() => setIsOpen(!isOpen)}>切换显示</Button> <Collapse in={isOpen}> <div> {/* 你的动态内容 */} </div> </Collapse> </div> ); }
该组件默认就是从上到下的滑入滑出效果,完全匹配你的需求,不需要额外编写CSS。
内容的提问来源于stack exchange,提问作者Zeno Dalla Valle
相关产品推荐
相关产品推荐

