CSS 模块和 CSS 关键帧动画

Dan*_*iel 5 css css-animations reactjs css-modules

我正在尝试使用 React、关键帧、CSS 模块(和 SASS)来制作一个简单的动画。问题在于 CSS 模块散列关键帧名称的方式与散列本地类的方式相同。

JS代码

//...

export default () => {
  const [active, setActive] = useState(false);
  return(
    <div className={active ? 'active' : 'inactive'}
      onClick={() => setActive(!active)}
    >content</div>
  )
}
Run Code Online (Sandbox Code Playgroud)

尝试使所有内容都全局化,将此源用作教程(不编译):

//default scope is local

@keyframes :global(animateIn) {
  0% { background: black; }
  100% { background: orange; }
}

@keyframes :global(animatOut) {
  0% { background: orange; }
  100% { background: black; }
}

:global {
  .active {
    background: orange;

    animation-name: animateIn;
    animation-duration: 1s;
  }

  .inactive {
    background: black;

    animation-name: animateOut;
    animation-duration: 1s;
  }
}
Run Code Online (Sandbox Code Playgroud)

改变这个也不起作用:

:global {
  @keyframes animateIn {
    0% { background: black; }
    100% { background: orange; }
  }

  @keyframes animateOut {
    0% { background: orange; }
    100% { background: black; }
  }
}
Run Code Online (Sandbox Code Playgroud)

另一种尝试(不起作用):

@keyframes animateIn {
  0% { background: black; }
  100% { background: orange; }
}

@keyframes animateOut {
  0% { background: orange; }
  100% { background: black; }
}

:global {
  .active {
    background: orange;

    :local {
      animation-name: animateIn;
    }
    animation-duration: 1s;
  }

  .inactive {
    background: black;

    :local {
      animation-name: animateOut;
    }
    animation-duration: 1s;
  }
}
Run Code Online (Sandbox Code Playgroud)

如何在 CSS 模块全局范围内使用关键帧?是否可以在全局范围类中使用局部范围关键帧?

Sal*_*Sal 7

你的第三次尝试几乎没问题,你只需要在&之前添加:local并确保它们之间有一个空格。通过这样做,您可以切换到选择器中的本地范围。

:global {
    .selector {
        & :local {
            animation: yourAnimation 1s ease;
        }
    }
}

@keyframes yourAnimation {
    0% {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

编译成

.selector {
    animation: [hashOfYourAnimation] 1s ease;
}
Run Code Online (Sandbox Code Playgroud)