Framer Motion如何仅在动画执行阶段为元素添加overflow:hidden样式
实现方案
你可以直接通过Framer Motion的transitionEnd属性实现需求,无需额外引入状态监听,修改后的代码如下:
const PanelBody = ({children, isFramed, isOpen}) => { const currentVariant = isOpen ? 'open' : 'closed' const loadFeatures = () => import('./framerMotionFeatures.js').then(res => res.default) return ( <LazyMotion features={loadFeatures}> <StyledPanelBody initial={currentVariant} animate={currentVariant} variants={{ closed: { height: 0, overflow: 'hidden' }, open: { height: 'auto', overflow: 'hidden', transitionEnd: { overflow: 'visible' } } }} transition={{ease: 'easeInOut', duration: 0.3}} isFramed={isFramed} isOpen={isOpen} > <div> {children} </div> </StyledPanelBody> </LazyMotion> ) }
逻辑说明
- 收起状态固定设置
overflow: hidden,避免内容溢出 - 展开动画执行过程中默认生效
overflow: hidden,防止动画过程中内容溢出覆盖下方元素 - 展开动画完全结束后,通过
transitionEnd配置将overflow改为visible,保证面板内部下拉列表等需要溢出展示的元素可以正常渲染
如果需要更灵活的自定义控制,也可以配合onAnimationStart和onAnimationComplete回调,结合本地状态变量来控制样式,实现效果和上述方案一致。
内容的提问来源于stack exchange,提问作者yilkur
相关产品推荐
相关产品推荐

