【问题标题】:Is this a good React practice?这是一个好的 React 实践吗?
【发布时间】:2017-12-05 19:06:21
【问题描述】:

我最近开始玩 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

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

【问题讨论】:

  • 为什么不直接把动画放到css类上呢?

标签: javascript css reactjs animation components


【解决方案1】:

React 很棒,但是在使用过 Javascript 时(您似乎已经使用过),它可能有点难以理解并且难以调整(根据经验)。 learncodeacademy 有一个很棒的关于 React 的 youtube 教程,它真的可以帮助你 understand react。您可能还想查看create react app 以获取设置 React 项目的简单方法。

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

此外,除非绝对必要,否则您不应使用 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

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

了解props 可能有点棘手,但如果您按照 learncodeacademy 的 youtube 教程进行操作,您就会明白。

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

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

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

【讨论】:

  • 谢谢你,这对我来说是纯金!我会检查你介绍的所有新概念。
猜你喜欢
  • 1970-01-01
  • 2012-04-08
  • 1970-01-01
  • 1970-01-01
  • 2015-01-04
  • 1970-01-01
  • 2019-10-22
  • 1970-01-01
  • 2014-09-23
相关资源
最近更新 更多