在具有样式组件的道具上触发动画

时间:2020-08-03 07:57:22

标签: reactjs styled-components

当其中一个道具等于true时,我试图在我的一个组件上运行动画。但是,我收到一个错误消息:“闪存不是功能”。

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>
  );
}

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

styled-components不支持您正在使用的语法,请检出this link

使用关键帧时会延迟注入关键帧,这就是它们的方式 被代码分割,因此您必须使用the css helper来共享样式 碎片

这是工作中的example。因此,我不得不将动画包装在该CSS帮助器中。