Material UI v5
在v5中,您可以使用keyframes
函数(默认情况下从emotion重新导出)来生成关键帧的样式表:
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
/sx
属性都在内部使用emotion,所以可以将相同的样式对象传递给sx
属性:
<Box
sx={{
backgroundColor: "pink",
width: 30,
height: 30,
animation: `${spin} 1s infinite ease`
}}
/>
![Codesandbox Demo](https://codesandbox.io/static/img/play-codesandbox.svg)
Material UI v4
在@Ryan's answer的基础上,这里有一些注意事项。如果你使用makeStyles
定义keyframe
,请记得在动画名称前加上$
前缀。我第一次就错过了这个小细节,导致我的代码无法工作,下面是一个示例:
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"
}
});
请在 GitHub 上关注 issue 以获取更多关于此问题的讨论。