我最近开始使用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我这样做是为了确保所有动画只有在页面正确加载时才会启动。我的问题是:这是正确的吗?如果不是,有没有更好的方法来达到同样的效果呢?
发布于 2017-07-02 20:31:17
React很棒,但是当你使用Javascript的时候(看起来你已经用过了),它可能会有点难以理解,也很难调整(根据经验)。在learncodeacademy的React上有一个很棒的youtube教程,它对你的understand react很有帮助。您可能还想看看create react app,寻找一种设置React项目的简单方法。
现在来回答你的问题:)这不是一个好的实践。React有自己的名为componentDidMount的"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在本例中,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。这意味着没有状态。
这意味着我不需要定义扩展component的类,我只需要使用一个常量。我也不需要定义渲染或返回,因为只有一个元素( div)被返回,不需要括号。在学习React时,这不是你最初需要担心的事情,但这是一个很好的实践。
https://stackoverflow.com/questions/44869877
复制相似问题