V5
在 v5 中,您可以使用该keyframes函数(默认情况下从情感重新导出)生成关键帧的样式表:
import { styled } from '@mui/material/styles';
import { keyframes } from '@mui/system';
const spin = keyframes`
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
`;
const RotatedBox = styled("div")({
  backgroundColor: "pink",
  width: 30,
  height: 30,
  animation: `${spin} 1s infinite ease`
});
因为styled/ sxprop 内部都使用了情感,所以你可以将相同的样式对象传递给sxprop:
<Box
  sx={{
    backgroundColor: "pink",
    width: 30,
    height: 30,
    animation: `${spin} 1s infinite ease`
  }}
/>

V4
只是在@Ryan 的回答之上的一些注释。如果您定义keyframeusing makeStyles. 请记住在动画名称前加上$. 我第一次错过了这个小细节,我的代码不起作用,在下面的例子中
const useStyles = makeStyles({
  "@keyframes fadeIn": {
    "0%": {
      opacity: 0,
      transform: "translateY(5rem)"
    },
    "100%": {
      opacity: 1,
      transform: "translateY(0)"
    }
  },
  selector: {
    animation: "$fadeIn .2s ease-in-out"
  }
});
代替
animation: "fadeIn .2s ease-in-out"
它应该是
animation: "$fadeIn .2s ease-in-out"
但是如果你keyframe在全局范围内定义。这里不需要前缀
const useStyles = makeStyles({
  "@global": {
    "@keyframes fadeIn": {
      "0%": {
        opacity: 0,
        transform: "translateY(5rem)"
      },
      "100%": {
        opacity: 1,
        transform: "translateY(0)"
      }
    }
  },
  selector: {
    animation: "fadeIn .2s ease-in-out" // --> this works
  }
});
请在 github 上关注此问题以获取有关此问题的更多讨论。