您可以在组件上内联使用样式化组件关键帧吗?

时间:2020-08-23 01:16:34

标签: reactjs styled-components

我正在尝试在我的应用中创建一个闪烁的星形效果。我创建了一个数组并遍历整个数组以获取“星” div的数量,然后使用样式化的组件对星进行样式化。我试图为它们分别设置动画,但是要做到这一点,我必须在循环时创建div时将属性在线内随机化。尝试在样式化组件中获取随机值会为每个div赋予相同的值。我的代码当前如下:

import React from 'react';
import styled, { keyframes, css } from 'styled-components'
import styles from './Stars.module.scss'

const flicker = keyframes`
    0%,100% {
        opacity: 1;
    }
    50% {
        opacity: 0.2;
    }

`
const Star = styled.div`
    position: absolute;
    width: 5px;
    height: 5px;
    border-radius: 2px;
    background: white;
`
const StarContainer = styled.div`
    position: absolute;
    top: 0;
    left: 0;
    overflow: hidden;
    width: 100%;
    height: 100%;
`

const vpHeight = window.innerHeight;
const vpWidth = window.innerWidth;

const starCount = () => {
    const count = []
    for(let i = 1; i <= 300; i++){
        count.push(i)
    }
    return count
}

const Stars = () => {
    return (
        <StarContainer id='star-container'>
            {starCount().map((star, i) => (
                <Star style={{
                    animation: `${Math.floor(Math.random() * 8)}s ${flicker} infinite`,
                    top: `${Math.floor(Math.random()*vpHeight)}px`,
                    left: `${Math.floor(Math.random()*vpWidth)}px`
                }} />
            ))}
        </StarContainer>
    );
}

export default Stars;

但这会产生以下错误:Error: It seems you are interpolating a keyframe declaration (gvlTRP) into an untagged string. This was supported in styled-components v3, but is not longer supported in v4 as keyframes are now injected on-demand. Please wrap your string in the css\\ helper which ensures the styles are injected correctly. See https://www.styled-components.com/docs/api#css

我不确定如何继续。有没有办法在内联元素样式中包含styled-component关键帧?

1 个答案:

答案 0 :(得分:1)

最好使关键帧保持静态,然后执行以下操作:

// keep the keyframes declaration static
const flicker = keyframes`
  /* etc. */
`;

const Star = styled.div`
  animation: ${flicker} infinite;
  animation-duration: ${props => props.animationDuration};
`;

// later...

<Star animationDuration={Math.random() * 8} />