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

React JS用state切换按钮class时重渲染恢复初始样式问题求助

问题原因

你的问题是表单默认提交行为触发页面刷新导致的:按钮默认type属性为submit,如果按钮放置在<form>标签内部,点击后会自动触发表单提交、重载整个页面,页面重载后所有React state都会重置为初始值,所以会出现类名短暂切换后立刻恢复初始状态的现象。

解决方案

方案1:明确指定按钮类型

给所有按钮添加type="button"属性,明确标记为普通按钮,不会触发表单提交:

<button type="button" className={buttonColor1?styles.priceButtonWhite:styles.priceButtonGreen} onClick={() => changeColor(1)}>100</button>
<button type="button" className={buttonColor2?styles.priceButtonWhite:styles.priceButtonGreen} onClick={() => changeColor(2)}>200</button>
<button type="button" className={buttonColor3?styles.priceButtonWhite:styles.priceButtonGreen} onClick={() => changeColor(3)}>300</button>

方案2:阻止默认提交行为

如果业务需要保留表单提交能力,可以在点击事件中阻止默认行为,同时建议使用函数式更新state,避免闭包导致的状态更新异常:

const changeColor = (e, n) => {
    e.preventDefault();
    if (n==1){
        setButtonColor1(prev => !prev);
    }
    else if (n==2){
        setButtonColor2(prev => !prev);
    }
    else{
        setButtonColor3(prev => !prev);
    }
}

对应修改按钮的点击事件传参:

<button className={buttonColor1?styles.priceButtonWhite:styles.priceButtonGreen} onClick={(e) => changeColor(e, 1)}>100</button>
代码优化建议

你当前使用3个独立state管理按钮状态,可简化为单个数组state,降低冗余代码:

// 初始化状态,三个按钮默认都为白色
const [buttonColors, setButtonColors] = useState([true, true, true]);

// 统一切换函数
const changeColor = (index) => {
  setButtonColors(prev => {
    const newArr = [...prev];
    newArr[index] = !newArr[index];
    return newArr;
  })
}

// 按钮调用示例
<button type="button" className={buttonColors[0]?styles.priceButtonWhite:styles.priceButtonGreen} onClick={() => changeColor(0)}>100</button>
<button type="button" className={buttonColors[1]?styles.priceButtonWhite:styles.priceButtonGreen} onClick={() => changeColor(1)}>200</button>
<button type="button" className={buttonColors[2]?styles.priceButtonWhite:styles.priceButtonGreen} onClick={() => changeColor(2)}>300</button>

内容的提问来源于stack exchange,提问作者Tisa Maharjan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 21:39:00