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 时需要担心的事情,但这是一个很好的做法。