我有一个组件需要为其每个子组件设置不同的动画。
我正在使用 React Hooks 和 Material UI 来设计我的组件。
我的组件如下所示:
const useStyles = makeStyles({ // from material ui
root: {
position: 'relative',
},
child: {
position: 'absolute',
},
})
const Children = (props) => {
const { count } = props;
const classes = useStyles();
const elements = [];
// Generating random values for each child.
for (let i = 0; i < count; i += 1){
const randomX = Math.random() * 100;
const randomY = Math.random() * 100;
... other random variables
const delay = Math.random(); // I want to use this in my animation
const duration = Math.random() * (3 - 0.5) + 0.5; // I want to use this in my animation
elements.push({ ... all random variables mapped });
}
return (
<>
{elements.map(item => {
<div
key={item.x}
style={{
top: `${item.x}`,
left: `${item.y}`,
color: `${item.color}`,
... and so forth
}}
className={classes.child}
/>
}
</>
);
};
const Parent = () => {
const classes = useStyles();
return (
<div className={classes.root}>
<Children count={5} />
</div>
);
};
我的问题是我希望为子元素触发不同的动画。我已经尝试为 makeStyles 样式添加一个关键帧动画部分,如果我只是在那里定义它,我可以轻松添加样式和关键帧动画,并且它有效!但是,据我所知,如果我在那里为每个子元素添加不同的参数,我会遇到问题。
const useStyles = makeStyles({
root: { ... },
child: {
...
animation: '$fade 2s 1s infinite', // This works but I can't add different values for each child
// I want to change duration and delay for each child
},
'@keyframes fade': {
'0%': { opacity: '0' },
'100%': { opacity: '1' },
},
})
我还尝试将我的关键帧动画添加到孩子的内联样式中,但这似乎根本不起作用。
<div
key={item.x}
style={{
top: `${item.x}`,
left: `${item.y}`,
color: `${item.color}`,
... and so forth
animation: `fade ${item.duration} ${item.delay} infinite`, // this does not work - not even with static values
}}
className={classes.child}
/>
我在这里发帖希望有人知道如何克服我的问题。让我知道你的想法。我很确定它是可能的StyledComponents,但我不想安装另一个样式库来解决这个非常具体的问题。
我很确定我在某个时候使用了 CSS 自定义变量var(--duration)& var(--delay),它可以做一些非常好的事情(甚至可能解决这个问题),但截至今天,我一直无法找到有关该主题的任何可用内容。问题主要是我如何将自定义变量注入到我的样式中。如果您知道我需要如何设置,请告诉我。
提前致谢。