如何将背景JS动画集成到我的React应用程序中? [英] How do I integrate a background JS animation into my react app?

查看:105
本文介绍了如何将背景JS动画集成到我的React应用程序中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将React动画添加到组件中(我要使用的代码在这里 https://codepen.io/celli/pen/xZgpvN )。如果我有一个简单的HTML / CSS / Javascript设置,我会知道该怎么做,但是我对如何在React的上下文中以及单个组件的范围内集成此动画感到困惑。我在哪里将代码放在下面?如何在组件中引用它?

I'm trying to add a firefly animation into a component within react (and the code I'm trying to use is here https://codepen.io/celli/pen/xZgpvN). If I had a simple HTML / CSS / Javascript setup I'd know what to do, but I'm confused on how to integration this animation in the context of React and in the scope of a single component. Where do I put the code below? How do I reference it within the component?


var total=40,
    container=document.getElementById('container'),
    w=window.innerWidth,
    h=window.innerHeight,
    Tweens=[],
    SPs=1;



for (var i=total;i--;){ 
    var Div=document.createElement('div');
    TweenLite.set(Div,{attr:{class:'dot'},x:R(w),y:R(h),opacity:0});
    container.appendChild(Div); Anim(Div);  Tweens.push(Div);
};

function Anim(elm){ 
    elm.Tween=TweenLite.to(elm,R(20)+10,{bezier:{values:[{x:R(w),y:R(h)},{x:R(w),y:R(h)}]},opacity:R(1),scale:R(1)+0.5,delay:R(2),onComplete:Anim,onCompleteParams:[elm]})
};

for(var i=total;i--;){
  Tweens[i].Tween.play()};


function R(max){return Math.random()*max};

其次,我将CSS代码放在下面的位置?

Secondly, where do I put the CSS code below?

body{
  background-color: #222222;
  overflow:hidden;
}

.dot{
  width:4px;
  height:4px;
  position:absolute;
  background-color:#ff00cc;
  box-shadow:0px 0px 10px 2px #ff00cc;
  border-radius: 20px;
  z-index:2;
}

#container {
width:100%; 
height:100%;
}


推荐答案

与其他库集成可能是最好的起点。

首先,这是一个可以直接在StackOverflow上运行的示例。

Firstly, here's an example that can be run directly on StackOverflow.

const {
  useRef,
  useLayoutEffect,
} = React
// import React, { useRef, useLayoutEffect } from 'react';

function R(max) {
  return Math.random() * max
};

function Background(props) {
  const {
    total = 40
  } = props
  const ref = useRef()

  useLayoutEffect(() => {
    const contanier = ref.current
    const w = window.innerWidth
    const h = window.innerHeight
    const dots = []

    function addAnimation(elm) {
      return TweenLite.to(elm, R(20) + 10, {
        bezier: {
          values: [{
            x: R(w),
            y: R(h)
          }, {
            x: R(w),
            y: R(h)
          }]
        },
        opacity: R(1),
        scale: R(1) + 0.5,
        delay: R(2),
        onComplete: addAnimation,
        onCompleteParams: [elm]
      })
    }

    for (let i = 0; i < total; i++) {
      const div = document.createElement('div')
      TweenLite.set(div, {
        attr: {
          class: 'dot'
        },
        x: R(w),
        y: R(h),
        opacity: 0
      })
      container.appendChild(div);
      const dot = addAnimation(div)
      dot.play()
      dots.push(dot)
    }
    
    return () => {
      // Clear animations and whatever here
      dots.forEach(dot=>dot.kill())
      container.innerHTML = ''
    }
  }, [total])
  return <div className="fireflies" ref={ref} />
}

function App() {
  return <Background total={25} / >
}

ReactDOM.render( <App / > , document.querySelector("#container"))

body {
  background-color: #222222;
  overflow: hidden;
}

.dot {
  width: 4px;
  height: 4px;
  position: absolute;
  background-color: #ff00cc;
  box-shadow: 0px 0px 10px 2px #ff00cc;
  border-radius: 20px;
  z-index: 2;
}

.fireflies {
  width: 100%;
  height: 100%;
}

<div id="container" />

<!-- React -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<!-- TweenMax -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.15.0/TweenMax.min.js"></script>

现在解释。

一个简短的注释:前面提到的与其他库集成页面现在使用类组件,但是我喜欢使用功能组件,因为钩子是ffᵤₜᵤᵣₑ。我还将一些代码从旧es5转换为新的现代es6,因为现代js是ₜₕₑfᵤₜᵤᵣₑ。

A quick side note: the previously mentioned Integrating With Other Libraries page as of right now uses class components, but I like to use functional components because hooks are ₜₕₑ fᵤₜᵤᵣₑ. I also converted some of the code from old es5 to new modern es6 because modern js is ₜₕₑ fᵤₜᵤᵣₑ.

基本思想是,在首次安装组件时,您将在 useLayoutEffect 挂钩。基本上,这可以归结为将当前的大多数js扔到该钩子中。

The basic idea is that when your component is first mounted, you run all the initial setup inside of a useLayoutEffect hook. That essentially boils down to throwing most of your current js inside of that hook.

该组件唯一需要渲染的就是将包含所有点的div。

The only thing the component needs to render is the div that will contain all of the dots.

这里的优点是通过react,您可以使用props控制动画的各个方面-在示例中通过允许 total 变量作为道具传递。

The advantage here is that with react, you get to control aspects of your animation with props--demonstrated in the example by allowing the total variable to be passed as a prop.

此外,由于React提供了一种通过 useRef 挂钩,您可以使用而不是 document.querySelector('#contanier')

Also, since React provides a way to get a reference to a dom node via the useRef hook, you can use that instead of document.querySelector('#contanier').


我在哪里放CSS

Where do I put the CSS

最好的地方实际上取决于您如何设置反应应用程序。

The best place really depends on how you set up your react application.

如果某处有HTML模板,则可以像在其他任何p一样在其中放置样式标签或链接标签。

If you have an HTML template somewhere, you can just throw a style tag or a link tag in there as you would any other project.

如果您使用create-react-app或具有类似的设置,则可以通过导入样式表,方法是使用 css模块,或修改 src / index.css

If you used create-react-app or have a similar setup then you might just import them into your component by importing the stylesheet, by using css modules, or by modifying src/index.css.

另一种选择是使用css-in-js解决方案,例如 emotion styled -components ,但是这些组件可能需要一点时间来适应。

Another option is to use css-in-js solutions such as emotion or styled-components but those will probably take a little getting used to.

这篇关于如何将背景JS动画集成到我的React应用程序中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆