2017-07-02 54 views
0

我最近开始玩React。为了动画我的组件(使用CSS animation),我已经把这个代码块在我index.js这是一个很好的React练习吗?

// 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 

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

+0

为什么不把你的动画放在css类上? –

回答

0

反应很棒,但是当使用Javascript(好像你有)时,理解和难以调整(从经验)可能有点棘手。在React上有一个很棒的YouTube教程learncodeacademy,它真的可以帮助你understand react。您可能还想看看create react app以便设置React项目。

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

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

反应的美丽之处在于使用状态。

你的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可以是一个有点棘手,但如果按照YouTube的教程由learncodeacademy,你会得到它。

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

这是因为它是stateless。这意味着什么只是没有国家。

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

+0

谢谢,这对我来说是纯金!我会检查你介绍的所有新概念。 –

相关问题