You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 05:39:53