首页 > 解决方案 > Material ui 5标签消失,点击时标签向左移动,点击的标签消失

问题描述

点击时标签消失,大部分代码来自material-ui docs。这里我使用的是material-ui 5。不明白为什么代码会这样。样式也来自 Material ui 5。这是一个简单的导航栏,有 5 个选项卡

导入反应,{ useState } from 'react'; 从 '@mui/material' 导入 { AppBar, Toolbar, Tabs, Tab, useScrollTrigger, Box, Button }; 从“@mui/material/styles”导入 { styled };从'../../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: 10,
      marginLeft: '25px',
      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 value={value} onChange={handleChange} sx={{ marginLeft: 'auto' }}>
                  <StyledTab label='Home' />
                  <StyledTab label='Services' />
                  <StyledTab label='The Revolution' />
                  <StyledTab label='About Us' />
                  <StyledTab label='Contact Us' />
                </Tabs>
                <StyledButton variant='contained' color='secondary'>
                  Free Estimate
                </StyledButton>
              </Toolbar>
            </AppBar>
          </ElevationScroll>
          <ToolbarMargin />
        </React.Fragment>
      );
    };
    
    export default Header;

标签: javascriptreactjsmaterial-ui

解决方案


选项卡感觉就像消失了一样,因为selected选项卡上的类与tabs. Inspect您可以在浏览器开发人员工具的选项卡中检查行为。

您需要为活动选项卡的背景和颜色使用不同的颜色。在这里,我更改了选项卡的颜色以通过组件的propactive演示差异,并使用类选择器来定位活动选项卡的类。sxTabs.Mui-selected

您还可以使用选项卡的textColor 道具为选项卡文本使用辅助颜色。

<Tabs
  // textColor="secondary"
  value={value}
  onChange={handleChange}
  sx={{
    marginLeft: "auto",
    "&& .Mui-selected": { // && are used to increase the specificity
       color: "#d1d1d1"
    }
  }}
>

我已经根据您的示例代码创建了沙箱。


推荐阅读