首页 > 解决方案 > React - 用动画注入内联样式

问题描述

我有一个组件需要为其每个子级设置不同的动画。

我正在使用 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),它可以做一些非常好的事情(甚至可以解决这个问题),但截至今天我一直无法找到任何可用的主题。问题主要是我如何将自定义变量注入到我的样式中。如果您知道我需要如何设置,请告诉我。

提前致谢。

标签: cssreactjsanimationmaterial-uiinline-styles

解决方案


我找到了我想要的解决方案。

它不起作用的原因是由于 Material UI makestyles 包中的“随机命名”。所以我最终做的是使用 makestyles 包中的动画源:

const useStyles = makeStyles({
  root: { ... }, 
  child: {
    ...
    animationName: '$fade',
  },
  '@keyframes fade': {
    '0%': { opacity: '0' }, 
    '100%': { opacity: '1' },
  },
})

然后更改内联样式的持续时间和延迟,如下所示:

<div
  key={item.x}
  style={{
    animationDuration: `${item.duration}s´,
    animationDelay: `${item.delay}s`,
    animationIterationCount: 'infinite', 
  }}
  className={classes.child}
/>

推荐阅读