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

侧边菜单滑动动画与React状态控制异常问题求助

React侧边导航菜单滑动动画失效修复

你的问题核心在于styled-components的MenuWrapper没有接收React组件内的active状态,导致transform的条件判断完全没生效——因为MenuWrapper根本不知道active变量的存在,始终使用默认逻辑,自然不会触发滑动动画。

修复步骤:

  • 给MenuWrapper传递active状态
    在JSX中渲染MenuWrapper时,把组件内的active状态作为props传进去:

    <MenuWrapper active={active}>
    
  • 修正styled组件的props接收逻辑
    styled-components的样式函数接收的是一个props对象,你需要从对象中解构出active属性,而不是直接把参数当作active:

    transform: ${({ active }) => (active ? 'translateX(0%)' : 'translateX(-100%)')};
    

修改后的关键代码片段:

const SideNav: React.FC = () => {
  const [active, setActive] = useState(false);

  return (
    <Wrapper>
      {/* 传递active props */}
      <MenuWrapper active={active}>
        <>
          <AntDMenu
            defaultSelectedKeys={['1']}
            defaultOpenKeys={['sub1']}
            mode='inline'
            theme='dark'
            items={items}
          ></AntDMenu>
          <SideBox />
        </>
      </MenuWrapper>
      <MenuButton
        size='large'
        shape='circle'
        type='primary'
        onClick={() => setActive(!active)}
      >
        {active ? <MenuUnfoldIcon /> : <MenuFoldIcon />}
      </MenuButton>
    </Wrapper>
  );
};

// 给styled组件添加TS类型定义并解构active属性
const MenuWrapper = styled.div<{ active: boolean }>`
  display: flex;
  position: fixed;
  left: 0;
  top: 0;
  width: 160px;
  height: 100%;
  transition: transform 300ms;
  transform: ${({ active }) => (active ? 'translateX(0%)' : 'translateX(-100%)')};
`;

注:由于使用TypeScript,给MenuWrapper的props加上类型定义<{ active: boolean }>可以避免类型报错。

内容的提问来源于stack exchange,提问作者Mikołaj Wittbrodt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 07:55:26