使用Material-UI的tab组件时,如何自定义选中tab的样式?

When using Material-UI's tab component, how do I customize the style for a selected tab?

我正在尝试在我的 React 应用程序中使用 Material-ui 选项卡组件 -- https://material-ui.com/api/tabs/。我已经像这样设置了我的标签栏

  <AppBar position="static">
    <Tabs
      classes={classes}
      value={value}
      variant="fullWidth"
      centered
      onChange={handleChange}
      aria-label="volunteer dashboard tabs"
    >
      <Tab label={proposedLabel} {...a11yProps(2)} />
      <Tab label={planningLabel} {...a11yProps(1)} />
      <Tab label={inProgressLabel} {...a11yProps(0)} />
      <Tab label={completedLabel} {...a11yProps(3)} />
    </Tabs>
  </AppBar>

我的问题是,如何自定义tab选中时的样式?文档列出了 "indicator" class,所以我使用这些样式

  root2: {
    width: "100%",
    flexGrow: 1,
    backgroundColor: theme.palette.background.paper,
  },
  root3: {
    paddingRight: theme.spacing(1),
    flexGrow: 1,
    width: "100%",
  },
  viewButtons: {
    marginTop: theme.spacing(2),
    marginBottom: theme.spacing(1),
  },
  indicator: {
    border: 0,
    borderBottom: "2px solid",
    "&:hover": {
      border: 0,
      borderBottom: "2px solid",
    },
  }

但是,这个class没有生效。正确使用什么 class 来正确设置所选标签的样式?

我相信您想更改指标的样式(选项卡底部的边框), 我遇到了同样的问题,但找到了一个解决方法,这个解决方案有点乱,但它有效,你需要将指标背景设置为透明并将样式应用于其内部 div ,如下所示,

indicator: {
    backgroundColor: 'transparent',
    '& > div': {
        width: '100%',
        backgroundColor: theme.palette.primary.main,
        '&:hover': {
            backgroundColor: theme.palette.secondary.main,
        },
    },
},

悬停仅在您将鼠标悬停在指示器上时有效, 如果您想在将鼠标悬停在选项卡上时更改指示器颜色, 您需要将样式应用到根。

active 指标实际上是 tab 组件的一部分,而不是选项卡组件。如果你检查里面,你会看到一个 selected 道具(它将是 .Mui-selected)。

您应该使用带有 MuiThemeProvider 的 createMuiTheme 来设置样式:

const theme = createMuiTheme({
  overrides: {
    MuiTab: {
      root: {
        "&.Mui-selected": {
          background: "red"
        }
      }
    }
  }
});

这是一个工作示例:https://codesandbox.io/s/mui-theme-style-selected-tab-pe03k?file=/demo.js