首页 > 解决方案 > 使用 Material-UI 的标签组件时,如何自定义选中标签的样式?

问题描述

我正在尝试在我的 React 应用程序中使用 Material-ui Tab 组件——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>

我的问题是,如何在选择选项卡时自定义选项卡的样式?文档列出了“指标”类,所以我使用这些样式

  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",
    },
  }

但是,这个类没有生效。为了正确设置所选选项卡的样式,使用什么合适的类?

标签: reactjstabsmaterial-ui

解决方案


活动指示器实际上是选项卡组件的一部分,而不是选项卡之一。如果您检查内部,您会看到一个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


推荐阅读