如何使用react-spring Transition实现组件挂载/卸载时高度到auto的动画
用react-spring Transition组件实现height 0到auto的过渡动画
直接操作height: 'auto'在react-spring里没法实现平滑过渡,因为CSS动画无法识别auto这个动态值——它需要具体的数值才能计算过渡曲线。
目前最可行的方案就是你提到的通过max-height模拟过渡,核心思路是:
- 初始状态设置
max-height: 0,同时隐藏溢出内容 - 过渡时把
max-height设为一个足够大的固定值(比如1000px,只要超过内容实际高度就行) - 配合
opacity等其他属性增强动画效果
下面是一个简化的实现示例:
import { useState } from 'react'; import { useTransition, animated } from 'react-spring'; function App() { const [show, setShow] = useState(false); const transitions = useTransition(show, { from: { maxHeight: 0, opacity: 0 }, enter: { maxHeight: 1000, opacity: 1 }, leave: { maxHeight: 0, opacity: 0 }, config: { duration: 300 }, }); return ( <div> <button onClick={() => setShow(!show)}>切换内容</button> {transitions((style, item) => item && ( <animated.div style={{ ...style, overflow: 'hidden', background: '#f0f0f0', padding: '0 16px', }} > <p>这是一段动态展开/收起的内容,高度会自适应内容长度</p> <p>可以添加更多行文本测试效果</p> </animated.div> ) )} </div> ); } export default App;
需要注意的细节:
max-height的取值要合理,太大可能导致动画后期有延迟感,太小则会截断内容- 必须设置
overflow: hidden,否则内容会在max-height: 0时仍然显示 - 如果内容高度变化很大,可以结合
useRef获取实际内容高度,动态设置max-height的目标值,让动画更精准
内容的提问来源于stack exchange,提问作者user940912
相关产品推荐
相关产品推荐

