【问题标题】:Styled-components, SVG not animating样式化组件,SVG 没有动画
【发布时间】:2020-08-22 21:54:34
【问题描述】:

我在 React 旁边使用 styled-components 并且我有这样的组件:

import styled, { keyframes } from 'styled-components'
import { ReactComponent as SpinnerIcon } from './spinner.svg'

const rotate = keyframes`
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
`

const Spinner = styled(SpinnerIcon)`
    margin-top: 50px;
    animation: ${rotate} 2s ease-in infinite;
`

export default Spinner

当我像这样使用这个组件时:

<Spinner width='50px' height='50px' />

我看到了这个组件,但它没有动画。怎么了?

【问题讨论】:

    标签: css reactjs styled-components


    【解决方案1】:

    试试这个:

      const Spinner = styled.img.attrs({
          src: SpinnerIcon,
        })`
            margin-top: 50px;
            animation: ${rotate} 2s ease-in infinite;
    

    如果这对您不起作用,请也分享您的 svg 文件。此外,您可能需要使用 linear 函数而不是 ease-in `

    【讨论】:

    • 这有点用。但我得到一些错误。 src 属性必须是一个不能传递 SpinnerIcon 的字符串,但是当我给它'./spinner.svg'时,我看到一个动画但没有图标,只有这个没有找到的东西。
    • 使用默认导入:将 ReactComponent 导入为 SpinnerIcon from './spinner.svg'
    • 当我像这样导入 import { ReactComponent as SpinnerIcon } from './spinner.svg' 我得到这个长错误:Argument of type '{ src: React.FunctionComponent&lt;React.SVGProps&lt;SVGSVGElement&gt; &amp; { title?: string | undefined; }&gt;; }' is not assignable to parameter of type 'Attrs&lt;Pick&lt;DetailedHTMLProps&lt;ImgHTMLAttributes&lt;HTMLImageElement&gt;, HTMLImageElement&gt;, "slot" | ... 264 more ... | "onTransitionEndCapture"&gt; &amp; { ...; }, Partial&lt;...&gt; &amp; { ...; }, any&gt;
    • 还有这个:ype 'FunctionComponent&lt;SVGProps&lt;SVGSVGElement&gt; &amp; { title?: string | undefined; }&gt;' is not assignable to type 'string'
    • 你是对的,我只需要像这样导入它:import SpinnerIcon from './spinner.svg'
    猜你喜欢
    • 2021-09-02
    • 2020-09-26
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    相关资源
    最近更新 更多