我希望能够点击按钮来增加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,但想在JS中以“React方式”执行此操作。
任何指针都将非常感谢!
答案 0 :(得分:2)
您的代码中存在一些小问题:
在您的按钮组件上,将onClick={this.makeAppear()}
更改为onClick={this.makeAppear}
。
很好地使用函数方法而不是对象方法来基于先前的状态变量更新状态变量。但是,您的语法很小。要么:
this.setState(prevState => (
{opacity: prevState.opacity + 0.2}
));
或
this.setState(prevState => {
return {opacity: prevState.opacity + 0.2}
});
无论你喜欢什么。
为您从key
返回的每个项目添加map()
属性:基本上:
{this.state.thoughts.map((thought, i) => (<p key={i}>{thought}</p>))}
您可以安全地使用i
作为密钥,因为thoughts
数组中项目的顺序将保持不变。有关密钥以及如何正确使用密钥的详细信息,请查看here。
<强>演示:强>
class ThoughtfulThoughts extends React.Component {
constructor() {
super();
this.state = {
opacity: 0.4,
thoughts:
[
"live and let leave",
"just pee yourself",
"who knows what 'laf' is?"
]
}
}
makeAppear = () => {
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 key={i}>{thought}</p>)}
</div>
<button onClick={this.makeAppear}>Think for me</button>
</div>
);
}
}
ReactDOM.render(<ThoughtfulThoughts />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>