Material UI:点击旋转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
相关产品推荐
相关产品推荐

