【问题标题】:Change background color on button click using JS使用JS更改按钮单击时的背景颜色
【发布时间】: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


【解决方案1】:

看起来在你的 setState 中你有颜色而不是颜色。

this.setState({colour:random})

【讨论】:

    【解决方案2】:

    这里的问题是在 setState 中,您提供了错误的状态变量名称。应该是

    this.setState({colour:random})
    

    【讨论】:

      猜你喜欢
      • 2014-10-09
      • 2017-08-02
      • 2014-10-10
      • 1970-01-01
      • 2019-04-14
      • 2014-10-07
      • 2015-03-29
      • 1970-01-01
      相关资源
      最近更新 更多