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

Mui Button点击后全部标签变色,如何仅保留激活标签为绿色?

问题解决:MUI页脚按钮点击后仅激活单个按钮保持绿色

错误原因分析

方案1问题

你定义的currentTab只固定对比第一个按钮的链接,所有按钮共用同一个样式变量,导致要么全是激活状态、要么全是默认状态,无法单独识别当前匹配的按钮。

方案2问题

使用了全局布尔状态isClicked,点击任意按钮都会将状态设为true,所有按钮的颜色判断都依赖这个全局状态,自然全部变绿。


解决方案

场景1:基于路由路径的激活(推荐,符合页脚导航常规逻辑)

当用户点击按钮跳转到对应页面后,根据当前路由路径自动匹配激活按钮,保持绿色状态。

import { useLocation } from 'react-router-dom';
import { Box, Button } from '@mui/material';
import { Link } from 'react-router-dom';

const Footer = () => {
  const location = useLocation(); // 使用react-router钩子获取当前路径

  const navButtons = [
    { button: "Services", link: "/services" },
    { button: "Featured Work", link: "/work" },
    { button: "About", link: "/about" },
    { button: "Contact", link: "/contact" },
  ];

  return (
    <Box display='flex' justifyContent='space-around' marginTop='50px'>
      {navButtons.map(({ button, link }, index) => {
        // 每个按钮单独判断当前路径是否匹配自身链接
        const isActive = location.pathname === link;
        return (
          <Button
            key={index}
            to={link}
            component={Link}
            sx={{
              fontSize: '16px',
              color: isActive ? 'green' : 'black',
              '&:hover': { color: 'green' },
              // 可选:给激活状态加额外样式,比如下划线
              textDecoration: isActive ? 'underline' : 'none'
            }}
          >
            {button}
          </Button>
        );
      })}
    </Box>
  );
};

export default Footer;

场景2:仅基于点击事件的激活(不依赖路由跳转)

如果不需要路由跳转,仅点击按钮后保持绿色,其他按钮恢复默认黑色,需要用状态记录当前激活的按钮标识(比如链接地址或索引)。

import { useState } from 'react';
import { Box, Button } from '@mui/material';
import { Link } from 'react-router-dom';

const Footer = () => {
  const [activeLink, setActiveLink] = useState(''); // 记录当前激活的链接

  const navButtons = [
    { button: "Services", link: "/services" },
    { button: "Featured Work", link: "/work" },
    { button: "About", link: "/about" },
    { button: "Contact", link: "/contact" },
  ];

  const handleClick = (link) => {
    setActiveLink(link); // 点击时更新激活的链接
  };

  return (
    <Box display='flex' justifyContent='space-around' marginTop='50px'>
      {navButtons.map(({ button, link }, index) => {
        const isActive = activeLink === link;
        return (
          <Button
            key={index}
            to={link}
            component={Link}
            onClick={() => handleClick(link)} // 传递当前按钮的链接
            sx={{
              fontSize: '16px',
              color: isActive ? 'green' : 'black',
              '&:hover': { color: 'green' }
            }}
          >
            {button}
          </Button>
        );
      })}
    </Box>
  );
};

export default Footer;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 21:57:44