首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >这是一个很好的React练习吗?

问这是一个很好的React练习吗?
EN

Stack Overflow用户
提问于 2017-07-02 18:37:05
回答 1查看 103关注 0票数 0

我最近开始使用React。为了使我的组件具有动画效果(使用CSS animation),我在我的index.js中放置了这段代码

代码语言:javascript
复制
// 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

我这样做是为了确保所有动画只有在页面正确加载时才会启动。我的问题是:这是正确的吗?如果不是,有没有更好的方法来达到同样的效果呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-02 20:31:17

React很棒,但是当你使用Javascript的时候(看起来你已经用过了),它可能会有点难以理解,也很难调整(根据经验)。在learncodeacademy的React上有一个很棒的youtube教程,它对你的understand react很有帮助。您可能还想看看create react app,寻找一种设置React项目的简单方法。

现在来回答你的问题:)这不是一个好的实践。React有自己的名为componentDidMount的"window.onload“

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

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

你的CSS值应该是一个状态。

这方面的一个例子是:

代码语言:javascript
复制
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

在本例中,MyComponent可能如下所示

代码语言:javascript
复制
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

理解props可能有点棘手,但如果你遵循learncodeacademy的youtube教程,你就会明白。

请注意,第二段代码要短得多。

这是因为它是stateless。这意味着没有状态。

这意味着我不需要定义扩展component的类,我只需要使用一个常量。我也不需要定义渲染或返回,因为只有一个元素( div)被返回,不需要括号。在学习React时,这不是你最初需要担心的事情,但这是一个很好的实践。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44869877

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档