【发布时间】:2021-04-06 04:47:51
【问题描述】:
我想在单击按钮时更改背景,但是当我单击按钮时状态为空,因为我无法更改背景颜色
import React,{Component} from "react"
const colors = ['red', 'green', 'blue', 'yellow', 'pink', 'purple']
class ChangeBagroundColour extends Component {
state= {
colour:""
}
handleColour= e => {
var random = colors[Math.floor(colors.length*Math.random())]
this.setState({colors:random})
console.log( this.state.colour,random)
}
render() {
return(
<div>
<div>
<b>Project 1:change baground colour</b>
</div>
<div style={{backgroundColor:this.state.colour}}>
<button onClick={this.handleColour}>Click me</button>
</div>
</div>
)
}
}
export default ChangeBagroundColour
【问题讨论】:
-
在构造函数中包含你的状态,并确保你在那里也绑定了 handleColour
标签: javascript node.js npm react-redux jsx