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

如何在Material UI中使用useState实现点击按钮切换特定按钮边框

问题解决:MUI按钮点击高亮功能修复

问题原因

MUI的Button组件不支持selected属性,你代码中使用的selected属性不会触发.Mui-selected类的添加,这是导致高亮样式失效的核心原因。同时初始状态selectedIndex2设为空字符串,和后续数字索引的比较逻辑也存在潜在不匹配。

解决方案

  1. 调整初始状态为-1(表示初始无选中按钮)
  2. 移除无效的selected属性,通过条件判断直接给选中按钮添加高亮样式
  3. 抽离公共样式避免代码重复,提升可维护性

修改后的完整代码

import * as React from "react";
import Button from "@mui/material/Button";
import Stack from "@mui/material/Stack";

export default function TestSample() {
    // 初始状态设为-1,代表无选中按钮
    const [selectedIndex2, setSelectedIndex2] = React.useState(-1);

    const handleListItemClick2 = (event, index) => {
      setSelectedIndex2(index);
    };

    // 公共按钮样式
    const baseButtonStyle = {
        width: 131,
        textTransform: "none",
        height: 42,
        borderRadius: 3,
        fontFamily: "Barlow Condensed",
        fontSize: "22px",
        "&.Mui-focusVisible": {
          border: "3px solid #F2A42A",
        },
        ":hover": {
          border: "3px solid #F2A42A",
        }
    };

    // 选中状态样式
    const selectedButtonStyle = {
        border: "3px solid #F2A42A",
    };

    return (
        <Stack spacing={2} direction="row" sx={{ mt: 3, ml: 5 }}>
            <Button
                variant="outlined"
                sx={{
                    ...baseButtonStyle,
                    // 条件判断:当前索引选中时应用高亮样式
                    ...(selectedIndex2 === 0 ? selectedButtonStyle : {})
                }}
                onClick={(event) => handleListItemClick2(event, 0)}
            >
                Dine In
            </Button>
            <Button
                variant="outlined"
                sx={{
                    ...baseButtonStyle,
                    ...(selectedIndex2 === 1 ? selectedButtonStyle : {})
                }}
                onClick={(event) => handleListItemClick2(event, 1)}
            >
                Pickup
            </Button>
            <Button
                variant="outlined"
                sx={{
                    ...baseButtonStyle,
                    ...(selectedIndex2 === 2 ? selectedButtonStyle : {})
                }}
                onClick={(event) => handleListItemClick2(event, 2)}
            >
                Delivery
            </Button>
        </Stack>
    );
}

额外说明

  • 点击按钮时,handleListItemClick2会更新选中索引,触发组件重新渲染
  • 通过对象扩展运算符...合并基础样式和选中样式,代码更简洁
  • 保留了原有的hover和focusVisible样式,保证交互一致性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 06:39:14