Javascript 这是一个好的做法吗?

Javascript 这是一个好的做法吗?,javascript,css,reactjs,animation,components,Javascript,Css,Reactjs,Animation,Components,我最近开始玩React。为了给我的组件设置动画(使用CSSanimation),我将这段代码放在了我的index.js: // some code here window.onload = () => { let myComponents = document.getElementsByClassName('componentThatHaveToBeAnimated') for (let c of myComponents) { // add dinam

我最近开始玩React。为了给我的组件设置动画(使用CSS
animation
),我将这段代码放在了我的
index.js

// some code here

window.onload = () => {
    let myComponents = document.getElementsByClassName('componentThatHaveToBeAnimated')

    for (let c of myComponents) {
        // add dinamically the CSS class containing the animation
    }
}

//some code here
我这样做是为了让舒尔相信,只有当页面正确加载时,所有动画才会启动。
我的问题是:这是正确的吗?如果不是,还有更好的方法来达到同样的效果吗?

React很棒,但是当使用Javascript时(就像你所看到的那样),理解起来有点棘手,而且很难调整(根据经验)。youtube上有一个很棒的关于React by的教程,这对你很有帮助。您可能还想寻找一种简单的方法来设置React项目

现在回答你的问题:)这不是一个好的做法。React有自己的“window.onload”,称为

此外,除非绝对必要,否则不应使用getElementBy

react的美妙之处在于使用状态

css值应该是一个状态

这方面的一个例子是:

import React, { Component } from 'react'
import MyComponent from './MyComponent'

class Animation extends Component {
  constructor() {
    super() //this always has to be called first in a constructor
    this.state = {
      animationCSS: '',
    }
    this.changeAnimationCSS = this.changeAnimationCSS.bind(this)
  }

  componentDidMount() {
    const getAnimationCSSFromDB = db.get(animationCSS) //This obviously does not work, but an example
    this.setState({
      animationCSS: getAnimationCSSFromDB
    })
  }

  changeAnimationCSS() {
    this.setState({
      animationCSS: //Whatever new css you may want
    })
  }

  render() {
    return (
      <MyComponent propertyForStylingAnimation={this.state.animationCSS} />
      <button onClick={this.changeAnimationCSS} label="Button" />
    )
  }
}
export default Animation
import React,{Component}来自“React”
从“/MyComponent”导入MyComponent
类动画扩展组件{
构造函数(){
super()//在构造函数中必须首先调用它
此.state={
动画CSS:“”,
}
this.changeAnimationCSS=this.changeAnimationCSS.bind(this)
}
componentDidMount(){
const getAnimationCSSFromDB=db.get(animationCSS)//这显然不起作用,只是一个例子
这是我的国家({
animationCSS:getAnimationCSSFromDB
})
}
changeAnimationCSS(){
这是我的国家({
animationCSS://您可能需要的任何新css
})
}
render(){
返回(
)
}
}
导出默认动画
在这种情况下,MyComponent可能看起来像这样

import React from 'react'

const MyComponent = props =>
  <div style={{ animate: props.propertyForStylingAnimation }}> // This does not work for animating since animate is not a css property.
    // Stuff
  </div>
export default MyComponent
从“React”导入React
常量MyComponent=props=>
//这不适用于动画,因为动画不是css属性。
//东西
导出默认MyComponent
理解可能有点棘手,但如果你遵循LearnCodecademy的youtube教程,你就会明白

请注意,代码的第二位要短得多

这是因为它是。这意味着根本不存在国家


这意味着我不需要定义扩展组件的类,我只需要使用一个常量。我也不需要定义render或return,因为只返回一个元素(div),不需要括号。在学习React时,您不必担心这一点,但这是一个很好的实践。

为什么不将动画放在css类上呢?谢谢,这对我来说是纯金!我会检查你介绍的所有新概念。