I want to change background on button click but when I click the button the state is empty because of that i am not able to change background color
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
It looks like in your setState you have colors instead of colour.
this.setState({colour:random})
The issue here is in setState you are giving wrong state variable name. It should be
this.setState({colour:random})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.