【问题标题】:Trigger animation on props with styled components在带有样式组件的道具上触发动画
【发布时间】:2020-08-03 07:57:22
【问题描述】:

当其中一个道具等于 true 时,我试图在我的一个组件上运行动画。但是,我收到“flash 不是函数”的错误。

https://codesandbox.io/s/wizardly-moser-tet99?file=/src/App.js:0-606

import React, { useState } from "react";
import styled, {keyframes} from "styled-components";

const flash = keyframes`
  from {
      opacity: 0;
      }

      to {
      opacity: 1;
      }
`;

const StyledTile = styled.div`
    width: 100px;
    height: 100px;
    background-color: pink;
    animation: ${props => props.animate ? flash `0.3s linear 3` : `null`};
`

export default function App() {

  const [doAnimate, setDoAnimate] = useState(false);
  return (
    <div className="App">
      <StyledTile animate = {doAnimate}/>
      <button onClick = {() => setDoAnimate(true)}/>
    </div>
  );
}

【问题讨论】:

  • 您描述中的 URL 指向一个空沙箱。
  • 抱歉忘记保存了,现在可以了吗?
  • 是的,现在可以使用了。

标签: reactjs styled-components


【解决方案1】:

我使用了文档中提到的 css 助手 here

const StyledTile = styled.div`
  width: 100px;
  height: 100px;
  background-color: pink;
  animation: ${props =>
    props.animate &&
    css`
      ${flash} 0.3s linear 3
    `};
`;

这是sandbox

【讨论】:

    【解决方案2】:

    styled-components 似乎不支持您使用的语法,请检查this link

    关键帧在使用时会延迟注入,这就是它们的作用 进行代码拆分,因此您必须使用the css helper 共享样式 碎片

    这是一个有效的example。所以我不得不将动画包装在那个 CSS 助手中。

    【讨论】:

      猜你喜欢
      • 2019-04-11
      • 2020-07-12
      • 2020-06-06
      • 2021-05-10
      • 1970-01-01
      • 2017-05-16
      • 1970-01-01
      • 1970-01-01
      • 2021-08-27
      相关资源
      最近更新 更多