You need to enable JavaScript to run this app. React中如何使用useState实现点击按钮切换白红两色?
优惠活动
大模型
产品
解决方案
定价
更多

React中如何使用useState实现点击按钮切换白红两色?

问题原因

  • 背景色切换的逻辑被注释,且逻辑中误用了不存在的变量bg,你实际定义的状态变量名为prev
  • 你使用的Material UI Button组件设置了color="tertiary"属性,组件自带的背景色样式优先级高于普通行内样式,同时全局CSS中直接针对button标签设置的灰色背景也会干扰自定义样式

修复方案

  1. 调整状态逻辑,取消背景色样式的注释,删除Button组件的color="tertiary"属性避免自带样式冲突
  2. 可根据需求调整全局CSS的按钮样式,避免直接选中所有button标签影响组件样式

修复后代码

app.js

// 顶部引入必要依赖
import { useState } from 'react';
import { Box, Grid, Paper, Button } from '@mui/material';

function App() {
  const classes = useStyles()
  // 调整状态名为语义化命名,后续维护更清晰
  const [isExcluded, setIsExcluded] = useState(false)

  return (
    <div className="App">
      <header className="App-header">
        <Box
          sx={{
            display: 'grid',
            gap: 1,
            gridTemplateColumns: 'repeat(2, 1fr)',
            gridTemplateRows: 'auto',
            gridTemplateAreas: `"header header header header"
      "main main . sidebar"
      "footer footer footer footer"`
          }}
        >
          <Grid container spacing={12}>
            <Grid item md={12}>
              <Paper className=" "> Tag </Paper>
            </Grid>

            <Grid item xs={6} md={8}>
              <Box
                className={clsx(classes.containerBox, classes.containerBox)}
              ></Box>

              <Button
                id="excluded"
                onClick={() => setIsExcluded(prev => !prev)}
                href="# "
                variant="contained"
                size="medium"
                style={{
                  fontSize: 20,
                  backgroundColor: isExcluded ? "red" : "white",
                  color: isExcluded ? "white" : "#000" // 可选:适配背景调整文字颜色,提升可读性
                }}
              >
                Exclude
              </Button>
            </Grid>
          </Grid>
        </Box>
      </header>
    </div>
  )
}

app.css 调整建议

如果不需要全局按钮的灰色背景,可删除或修改以下全局样式,避免影响所有按钮组件:

/* 原全局按钮样式,可删除或改为类选择器限制作用范围 */
button {
  padding: 10px 20px;
  margin: 5px;
  background-color: grey;
  border-radius: 5px;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 02:48:03