React:用于简单动画的 document.createElement 的替代品?

时间:2021-03-21 21:29:28

标签: javascript html reactjs

我用 HTML/CSS 制作了一个简单的动画来创建粒子,使用 CSS 动画让它们向上浮动,然后在超时时消失。我想将其转换为 React 应用程序的组件,但我知道直接操作 DOM 是不好的。我能够让一切正常工作,但我觉得使用 document.createElement 可能很糟糕。 反应代码:

import './ParticleWindow.css';
import React, {useRef}  from 'react';

function ParticleWindow(){

    const myBG = useRef();

    function createParticle(){
        if(myBG.current){
        const particle = document.createElement('span');
        var size = Math.random() * 30;
        particle.style.width = 20 + size + 'px';
        particle.style.height = 20 + size + 'px';
        var domRect = myBG.current.getBoundingClientRect();
        particle.style.top = Math.random() * domRect.height + 'px';
        particle.style.left = Math.random() * domRect.width + 'px';
        myBG.current.appendChild(particle);
        particle.className = "floating_particle";
        setTimeout(()=>{
            particle.remove();
        }, 5000);
        }
    }

    setInterval(createParticle, 150);


    return <div id="particle_bg" ref={myBG} className="particleWindow"></div>
}

export default ParticleWindow;

CSS:

.particleWindow{
    width: 90%;
    height: 600px;
    background: black;
    position: relative;
}


.floating_particle{
    position: absolute;
    pointer-events: none;
    background: greenyellow;
    animation: animate 5s linear infinite;
}

@keyframes animate{
    0%{
        transform: scale(0) translateY(0) rotate(0deg);
        opacity: 0;
    }
    10%{
        opacity: 1;
    }
    90%{
        opacity: 1;
    }
    100%{
        transform: scale(1) translateY(-500%) rotate(360deg);
        opacity: 0;
    }
}

我应该使用 useState 来跟踪屏幕上的所有粒子,然后将数组映射到里面吗?对于没有 React 的超级简单的事情来说,这似乎是一个非常麻烦的解决方案。屏幕上还有大量的颗粒。

是否有我应该使用的 document.createElement 的替代方案?您是否注意到我的代码有任何其他问题?

请注意,我试图更广泛地了解 HTML/CSS/JS 动画如何转移到 React 中,这是我尝试作为练习练习的内容。

0 个答案:

没有答案