MUI 5中使用Styled API实现关键帧动画失效问题求助
解决MUI 5 Styled API按钮Hover动画不工作的问题
我帮你找出了代码里的几个关键问题,调整后就能正常运行了:
问题分析
- Keyframes语法错误:你在每个关键帧结束后加了多余的逗号,这会导致CSS解析失败,动画根本无法被识别。
- 未调用keyframes生成函数:
getAnimation是一个返回keyframes对象的函数,你直接写${getAnimation}而没有调用它(getAnimation()),相当于把函数本身当成了动画值,自然不会生效。 - 缺少动画时长:只设置了
infinite(无限循环)的迭代次数,但没有指定动画时长(比如1s),默认时长为0,肉眼完全看不到动画效果。
修正后的完整代码
import Button from "@mui/material/Button"; import { styled } from "@mui/material/styles"; import { keyframes } from "@emotion/react"; // 修复keyframes的多余逗号问题,同时规范关键帧的空格格式 const getAnimation = () => keyframes` 0% { transform: translate(1px, 1px) rotate(0deg); } 10% { transform: translate(-1px, -2px) rotate(-1deg); } 20% { transform: translate(-3px, 0px) rotate(1deg); } 30% { transform: translate(3px, 2px) rotate(0deg); } 40% { transform: translate(1px, -1px) rotate(1deg); } 50% { transform: translate(-1px, 2px) rotate(-1deg); } 60% { transform: translate(-3px, 1px) rotate(0deg); } 70% { transform: translate(3px, 1px) rotate(-1deg); } 80% { transform: translate(-1px, -1px) rotate(1deg); } 90% { transform: translate(1px, 2px) rotate(0deg); } 100% { transform: translate(1px, -2px) rotate(-1deg); } `; const StyledButton = styled((props) => { const { ...other } = props; return <Button {...other} />; })(({ theme }) => ({ ":hover": { // 调用getAnimation函数生成动画,并添加1秒的时长参数 animation: `${getAnimation()} 1s infinite` }, backgroundColor: "#2699FB", color: "#FFFFFF" })); const App = () => { return ( <StyledButton variant="contained"> My button </StyledButton> ) } export default App
额外说明
如果hover时MUI默认的按钮过渡样式和你的动画冲突,可以尝试给animation属性加!important(应急可用,不推荐长期使用),或者通过嵌套&:hover的写法来提升样式优先级。你之前参考的makeStyles方案和Styled API核心逻辑一致,只是语法不同,本质都是依赖Emotion处理keyframes,修正这些细节问题后就能正常工作了。
内容的提问来源于stack exchange,提问作者user10613856
相关产品推荐
相关产品推荐

