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

Material UI:点击旋转IconButton,匹配Collapse组件展开/收起状态

实现IconButton点击时图标旋转配合Collapse展开/隐藏

你可以通过动态控制图标的旋转样式来实现需求,利用expanded状态切换图标的transform属性,具体实现如下:

完整代码示例

import { useState } from 'react';
import { Box, IconButton, Collapse } from '@mui/material';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';

const YourComponent = () => {
  const [expanded, setExpanded] = useState<boolean>(false);

  const handleExpand = () => {
    setExpanded(!expanded);
  };

  return (
    <Box>
      <IconButton onClick={handleExpand}>
        {/* 根据展开状态设置图标旋转角度 */}
        <ExpandMoreIcon 
          style={{ 
            transition: 'transform 0.3s ease', // 添加平滑过渡动画
            transform: expanded ? 'rotate(180deg)' : 'rotate(0deg)' 
          }} 
        />
      </IconButton>
      <Collapse in={expanded}>Hello</Collapse>
    </Box>
  );
};

export default YourComponent;

实现说明

  • 依赖expanded状态动态修改ExpandMoreIcon的旋转角度:展开时旋转180度(图标指向上方),收起时恢复初始角度(图标指向下方)
  • 添加transition属性让旋转过程带有平滑动画,优化交互体验
  • 保持Collapse组件的in属性与expanded状态绑定,同步控制内容的展开/隐藏

内容的提问来源于stack exchange,提问作者code_learner93

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 20:25:56