![](/img/trans.png)
[英]How to change background color using color picker without click on button?
[英]Change background color on button click using JS
我想在單擊按鈕時更改背景但是當我單擊按鈕時 state 是空的,因為我無法更改背景顏色
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
看起來在你的 setState 中你有 colors 而不是顏色。
this.setState({colour:random})
這里的問題是在 setState 你給出了錯誤的 state 變量名。 它應該是
this.setState({colour:random})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.