Material UI 5点击标签页时Tab消失、标签左移问题求助
问题原因
- 未给每个Tab显式指定value属性:MUI 5的Tabs组件默认按子元素索引匹配选中值,自定义Tab组件时易出现匹配异常,导致选中态计算错误。
- 自定义Tab样式未覆盖选中态规则:仅设置了普通状态下Tab文字为白色,MUI默认选中态Tab文字会继承主题主色,而AppBar默认背景就是主题主色,文字和背景同色就会出现“消失”的视觉效果。
- 样式规则冲突:自定义StyledTab时设置了无单位的
minWidth:10(默认解析为10px),和MUI Tab默认的尺寸计算逻辑冲突,选中时会触发布局重排,出现整体左移的异常。
修复方案
修改StyledTab样式规则,同时给每个Tab显式指定value属性,修改后的完整代码如下:
import React, { useState } from 'react'; import { AppBar, Toolbar, Tabs, Tab, useScrollTrigger, Box, Button } from '@mui/material'; import { styled } from '@mui/material/styles'; import logo from '../../assets/logo.svg'; const ElevationScroll = props => { const { children } = props; const trigger = useScrollTrigger({ disableHysteresis: true, threshold: 0, }); return React.cloneElement(children, { elevation: trigger ? 4 : 0, }); }; const ToolbarMargin = styled('div')(({ theme }) => ({ ...theme.mixins.toolbar, marginBottom: '3em', })); const StyledTab = styled(Tab)(({ theme }) => ({ ...theme.typography.tab, minWidth: 'auto', // 替换原冲突的10,适配内容宽度 marginLeft: '25px', color: 'white', // 补充选中态样式规则 '&.Mui-selected': { color: 'white' } })); const StyledButton = styled(Button)(({ theme }) => ({ ...theme.typography.estimate, borderRadius: '50px', marginLeft: '50px', marginRight: '25px', height: '45px', })); const Header = props => { const [value, setValue] = useState(0); const handleChange = (e, newvalue) => { setValue(newvalue); }; return ( <React.Fragment> <ElevationScroll> <AppBar position='fixed'> <Toolbar disableGutters={true}> <Box component='img' sx={{ height: '7em' }} alt='company logo' src={logo} /> {/* 给Tabs添加flexShrink:0避免被挤压偏移 */} <Tabs value={value} onChange={handleChange} sx={{ marginLeft: 'auto', flexShrink: 0 }}> {/* 每个Tab显式指定对应value */} <StyledTab label='Home' value={0} /> <StyledTab label='Services' value={1} /> <StyledTab label='The Revolution' value={2} /> <StyledTab label='About Us' value={3} /> <StyledTab label='Contact Us' value={4} /> </Tabs> <StyledButton variant='contained' color='secondary'> Free Estimate </StyledButton> </Toolbar> </AppBar> </ElevationScroll> <ToolbarMargin /> </React.Fragment> ); }; export default Header;
内容的提问来源于stack exchange,提问作者Diego Franco
相关产品推荐
相关产品推荐

