React中使用Animate.style实现FadeInLeft/FadeOutLeft动画异常问题
问题原因
你的Sidebar组件在isDisplayed为false时直接不返回任何内容,组件会被立即从DOM中卸载,根本没有机会执行fadeOutLeft动画。
解决方案
需要先保留组件在DOM中完成退出动画,再卸载组件。通过内部状态控制组件的渲染时机,结合动画结束事件实现:
修改后的Sidebar组件
import { useState, useEffect, useRef } from 'react'; import { Box, Text } from '@chakra-ui/react'; const Sidebar = ({ isDisplayed }) => { // 内部状态控制组件是否保留在DOM中 const [showSidebar, setShowSidebar] = useState(isDisplayed); const sidebarRef = useRef(null); useEffect(() => { if (isDisplayed) { // 显示时:先渲染组件,再触发进入动画 setShowSidebar(true); } else { // 隐藏时:先触发退出动画,动画结束后再卸载组件 const handleAnimationEnd = () => { setShowSidebar(false); sidebarRef.current?.removeEventListener('animationend', handleAnimationEnd); }; sidebarRef.current?.addEventListener('animationend', handleAnimationEnd); } }, [isDisplayed]); // 内部状态为false时才真正卸载组件 if (!showSidebar) return null; return ( <Box ref={sidebarRef} position="absolute" top={0} left={0} width="155px" height="100vh" bgColor="#1e1e1e" className={`${Styles.SidebarBox} animate__animated ${isDisplayed ? 'animate__fadeInLeft' : 'animate__fadeOutLeft'}`} > <Text color="#fff">Test</Text> </Box> ); }; export default Sidebar;
关键修改说明
- 新增
showSidebar内部状态,替代直接根据props判断是否渲染组件,避免立即卸载。 - 使用
useRef获取侧边栏DOM元素,监听animationend事件——当退出动画播放完成后,再将showSidebar设为false,完成组件卸载。 - 显示逻辑:先让组件出现在DOM中,再通过
isDisplayed触发fadeInLeft动画,保证进入动画正常执行。
额外注意事项
- 确保Animate.css的动画样式正确引入,没有被自定义样式覆盖动画时长、过渡属性。
- 如果需要兼容低版本浏览器,可以考虑添加
webkitAnimationEnd等前缀事件监听。
内容的提问来源于stack exchange,提问作者wldnr7_
相关产品推荐
相关产品推荐

