我有一个 Spinner 组件,它基本上是一个加载图标。我正在尝试将 Prop 传递给 JSS 样式,以便可以对其进行自定义。但如果我将 Prop 传递给关键帧,动画似乎不起作用。
下面是组件。当我使用动画 $spinnertest
时,它工作正常。如果我使用 $spinners
,它不会加载动画(在检查元素时,animation-name
甚至不会出现在类中,这让我相信它不会生成。)。
**问题 CodeSandBox 示例(只需将动画更改为 spinners
):https://codesandbox.io/s/exciting-shirley-pqt1o?fontsize=14&hidenavigation=1&theme=dark
const useStyles = makeStyles(theme => ({
root: props => ({
width: props.size,
height: props.size,
position: 'relative',
contain: 'paint',
display: 'inline-block',
}),
spinner: props => ({
width: props.size*0.3125,
height: props.size*0.3125,
background: props.color,
position: 'absolute',
animationDuration: props.duration,
animationIterationCount: 'infinite',
animationTimingFunction: 'ease-in-out',
}),
spinnerAnimation: {
animationName: '$spinners',
},
square2: props => ({
animationDelay: -props.duration/2,
}),
'@keyframes spinnertest': {
'25%': {
transform: 'translateX(22px) rotate(-90deg) scale(.5)',
},
'50%': {
transform: 'translateX(22px) translateY(22px) rotate(-180deg)',
},
'75%': {
transform: 'translateX(0) translateY(22px) rotate(-270deg) scale(.5)',
},
'to': {
transform: 'rotate(-1turn)',
},
},
'@keyframes spinners': props => ({
'25%': {
transform: `translateX(${props.translate}px) rotate(-90deg) scale(.5)`,
},
'50%': {
transform: `translateX(${props.translate}px) translateY(${props.translate}px) rotate(-180deg)`,
},
'75%': {
transform: `translateX(0) translateY(${props.translate}px) rotate(-270deg) scale(.5)`,
},
'to': {
transform: `rotate(-1turn)`,
},
}),
}));
export default function Spinner(props) {
const {duration, size, color} = props;
const classes = useStyles({
duration: duration,
size: size,
color: color,
translate: size*(1-0.3125),
});
return (
<Box className={classes.root}>
<Box className={clsx(classes.spinner, classes.spinnerAnimation)} />
<Box className={clsx(classes.spinner, classes.square2, classes.spinnerAnimation)} />
</Box>
)
}
Spinner.defaultProps = {
duration: 1800,
size: 32,
color: #fff,
}
最佳答案
我有一个周转解决方案,它有效(不是那么漂亮)。您可以将 withStyles
转换为柯里化(Currying)函数,该函数采用 keyframesProps
,并且在关键帧定义中您将使用 IIFE 返回对象及其属性:
const useStyles = keyframesProps => makeStyles((theme) => ({
... all other styles,
// you need to call an IIFE because keyframes doesn't receive a function
"@keyframes spinners": ((props) => ({
"25%": {
transform: `translateX(${props.translate}px) rotate(-90deg) scale(.5)`
},
"50%": {
transform: `translateX(${props.translate}px) translateY(${props.translate}px) rotate(-180deg)`
},
"75%": {
transform: `translateX(0) translateY(${props.translate}px) rotate(-270deg) scale(.5)`
},
to: {
transform: `rotate(-1turn)`
}
}))(keyframesProps)
}));
在您的组件中,您可以定义您的类
,例如:
const styleProps = {
duration: duration,
size: size,
color: color
}
const framesProps = {
translate: size * (1 - 0.3125)
}
const classes = useStyles(framesProps)(styleProps);
关于reactjs - 传递 Prop 时 JSS 关键帧不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66057748/