You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React如何实现点击三次切换颜色后恢复默认状态的按钮

React点击切换颜色解决方案

原代码问题梳理

  • 重复声明Button组件,存在命名冲突语法错误
  • 仅使用布尔值状态只能实现2种颜色切换,无法满足3次切换回到初始色的需求
  • 事件处理方法需要手动bind this,写法冗余

修复后完整实现代码

import React from 'react';

class ColorSwitchButton extends React.Component {   
  constructor(props){
    super(props); 
    this.state = {
      // 颜色索引,默认0对应初始色
      currentIndex: 0,
      // 颜色池:初始色 + 2种切换色,共3种,切换3次自动回到初始
      colorPool: [props.defaultColor, props.switchColor1, props.switchColor2]
    }
  }

  handleClick = () => {
    this.setState(prev => ({
      // 取模运算实现循环,索引到3自动归零
      currentIndex: (prev.currentIndex + 1) % prev.colorPool.length
    }))
  }

  render(){
    const bgColor = this.state.colorPool[this.state.currentIndex]
    return (
      <div>
        <button style={{backgroundColor: bgColor}} onClick={this.handleClick}>
          切换颜色
        </button>
      </div>
    )
  }
}

class App extends React.Component {
  render(){
    return (
      <div>
        <ColorSwitchButton defaultColor="blue" switchColor1="red" switchColor2="green" />
      </div>    
    )
  }
}

export default App;

实现逻辑说明

  • 用数字类型的currentIndex替代原布尔值状态,支持多颜色索引定位
  • 总共有3种颜色,每次点击索引+1,通过% 3取模运算,当索引累加至3时自动回到0,刚好满足点击3次回到初始色的需求
  • 采用类属性箭头函数定义事件方法,省去手动bind this的操作
  • 颜色通过props传入,可灵活自定义切换的颜色值,若需要更多切换次数,只需扩充colorPool数组的长度即可

内容的提问来源于stack exchange,提问作者Noob Coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 16:57:00