2017-07-02 64 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

謝謝,這對我來說是純金!我會檢查你介紹的所有新概念。 –

相關問題