【发布时间】:2018-10-16 03:22:04
【问题描述】:
我希望能够在单击按钮时增加 DOM 元素的不透明度。
围绕 React 的概念,我认为这应该通过使用 state 和函数式 setState() 函数来完成。
但是,我不断遇到以下代码错误:
import React, { Component } from 'react'
class ThoughtfulThoughts extends Component {
state = {
opacity: 0.4,
thoughts:
[
"live and let leave",
"just pee yourself",
"who knows what 'laf' is?"
]
}
makeAppear = () => {
// TODO: this causes a "RangeError: Maximum call stack size exceeded"
this.setState(prevState => ({
opacity: prevState.opacity + 0.2
}))
}
render() {
return (
<div className="thoughtful-thoughts">
<div className="current-thought" style={{opacity: this.state.opacity}}>
{this.state.thoughts.map((thought, i) => (<p>{thought}</p>))}
</div>
<button onClick={this.makeAppear()}>Think for me</button>
</div>
)
}
}
export default ThoughtfulThoughts
我不想想use jQuery,也不想direct DOM manipulation,也不想 CSS transitions,但想以“React 方式”在 JS 中执行此操作。
任何指针将不胜感激!
【问题讨论】:
-
把
onClick={this.makeAppear()}改成onClick={this.makeAppear} -
^ 克里斯所说的。扩展它,超出堆栈大小的原因是因为每次渲染时,您都在调用该函数
onClick={this.makeAppear()}。该函数会更改状态,从而导致重新渲染。这种重新渲染调用该函数,它会改变状态——等等。这是一个无限循环。 -
你还需要用
()包裹{ opacity: prevState.opacity + 0.2 }否则使用return。