【问题标题】:React button onClick renders three color, How to make that button?React按钮onClick呈现三种颜色,如何制作那个按钮?
【发布时间】:2021-10-28 16:36:59
【问题描述】:

您好,我正在尝试在 React 中创建一个按钮,每次单击都会提供一种新颜色,这种情况会发生 3 次,然后它会返回默认选项。我尝试使用循环和一切,但仍然没有成功,有人可以帮忙吗?

代码:

import React from 'react';

class Button extends React.Component {   
  constructor(){
  super(); 
  this.state = {
      color_black: true,
    }
  }
  changeColor(){
          this.setState({color_black: !this.state.color_black})
  }
      render(){
      let bgColor = this.state.color_black ? this.props.color : this.props.color2
      return (
      <div>
          <button style={{backgroundColor: bgColor}} onClick={this.changeColor.bind(this)}>Button1</button>
      </div>
    )
  }
}

class Button extends React.Component {
      render(){
      return (
      <div>
          <Button color="blue" color2="red" />
          
      </div>    
    )
  }
}
export default Button;

【问题讨论】:

  • 为什么会有两个按钮组件?

标签: reactjs loops button colors click


【解决方案1】:

您可以拥有一组颜色并将其保留为常量。然后创建一个状态来保存数组的索引,从 0 开始。然后当你单击按钮时,增加索引并使用 array[index] 作为你的颜色。当 index=3 时重置为 0。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-12
    • 2023-01-19
    • 2013-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多