如何为MUI SVG图标添加点击旋转及过渡动画效果?
解决SVG图标旋转及过渡效果问题
你的代码存在几个关键问题导致图标无法旋转,同时可以通过添加CSS过渡实现平滑动画,以下是修复方案:
问题分析与修复点
- 变量名不匹配:你在
transform判断中使用了accordionExpanded,但实际定义的state变量是expanded,两者不一致导致逻辑失效。 - transform语法错误:CSS旋转的正确写法是
rotate(角度),而非transform(角度)——transform是属性名,rotate()是该属性的变换函数。 - 缺少过渡配置:需要为图标添加
transition属性,让旋转变化平滑生效。
修改后的完整代码
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 sx={{ // 修复变量名和transform语法 transform: expanded ? 'rotate(180deg)' : 'rotate(0deg)', // 添加过渡效果,调整延迟时间(你写的10s延迟过长,示例改为无延迟) transition: 'transform 100ms ease' }} /> </IconButton> <Collapse in={expanded}>Hello</Collapse> </Box> ); }; export default YourComponent;
额外说明
- 你原本写的
transition: all 100ms ease 10s中,最后一个值是延迟时间,10秒的延迟会让动画在点击后10秒才启动,通常不符合交互需求,示例中去掉了延迟;如果确实需要延迟,可以加回(比如transition: transform 100ms ease 10s)。 - 建议只针对
transform属性设置过渡,而非all,这样性能更优,避免触发不必要的属性动画。
内容的提问来源于stack exchange,提问作者code_learner93
相关产品推荐
相关产品推荐

