如何更改 MUI 中的活动选项卡颜色?

How to change active tab color in MUI?

如何更改活动选项卡的颜色?

我的意思是,这 pink 行,看图片。

您可以制作一个粉红色的 div,使用 JQuery 的 JavaScript 进行动画处理。它将被放置在绿色 div 中,颜色与选项卡相同。

嗯,你有两个选择:

您可以自定义主题:
http://www.material-ui.com/#/customization/themes

但最简单的方法是使用 inkBarStyle 属性.
您可以在 docs..
中看到它 示例:

<Tabs inkBarStyle={{background: 'blue'}}>...

虽然这是一个相当古老的问题,但它仍然引起了一些关注,对于我们这些使用多个和大量自定义主题的人来说,这是一个麻烦。我有一个更好的解决方案,可以让你根据主题定制不同的颜色

首先,创建一个 class 您可以通过这种方式将其添加到选项卡组件来挂钩

<Tabs
   onChange={this.handleChange}
   value={this.state.slideIndex}
   className="dashboard-tabs"> //this is what you need
       <Tab label="Main" value={0}/>
       <Tab label="Analytics" value={1}/>
       <Tab label="Live Widgets" value={2}/>
</Tabs>

请记住,我的选项卡和您的选项卡可能不同,因此请只注意 className 行。您可以随意命名。 1. 如果您希望不同的选项卡具有不同的下划线,请将其命名为有意义的名称,例如如果选项卡位于仪表板中则为 dashboard-tabs,如果它们是快速面板的一部分则为 quickpanel-tabs 等。 2. 如果您的选项卡将是本质上是一样的,将其更全局地命名为 material-tabs,现在您可以在任何地方使用 class,并且您的 css 无需再次创建即可工作。

现在,使用这个class作为一个钩子class并使用特异性来到达下划线,像这样

.dashboard-tabs > div{
    background-color: #333 !important;
}
.dashboard-tabs > div:nth-child(2) > div{
    background-color: #ddd !important;
}

不用担心 !important。使用 !important 是不好的禁忌,不过是一个大禁忌。你会没事的。

这是一个 SCSS 示例

.dashboard-tabs{
    > div{
        background-color: $bg-color-meddark !important;
        &:nth-child(2){
            > div{
                background-color: $brand-info !important;
            }
        }
    }
}

如果您使用多个主题,此解决方案将非常有用,因为(假设您的主题设置正确),您应该在上面的代码中附加一个动态主题 class 来更改您的 UI 从一种颜色到另一种颜色。所以,假设你有 2 个主题。 1 是浅色主题,使用 class light-theme 主题,2 是深色主题,使用 dark-theme class

现在,您可以按如下方式进行操作:

.light-theme .dashboard-tabs > div{
    background-color: #fff !important;
}
.light-theme .dashboard-tabs > div:nth-child(2) > div{
    background-color: #333 !important;
}
.dark-theme .dashboard-tabs > div{
    background-color: #333 !important;
}
.dark-theme .dashboard-tabs > div:nth-child(2) > div{
    background-color: #ddd !important;
}

有道理吗?

为什么我反对 InkBarStyle 解决方案?因为您要将一种背景颜色替换为另一种背景颜色,但仍然无法跨主题更改它

祝大家好运!

这是一个在您的项目中使用的主题模板:

'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

let _colors = require('material-ui/styles/colors');
let _colorManipulator = require('material-ui/utils/colorManipulator');
let _spacing = require('material-ui/styles/spacing');
let _spacing2 = _interopRequireDefault(_spacing);

function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : {default: obj};
}

exports.default = {
  spacing: _spacing2.default,
  fontFamily: 'Roboto, sans-serif',
  borderRadius: 2,
  palette: {
    primary1Color: _colors.grey50,
    primary2Color: _colors.cyan700,
    primary3Color: _colors.grey600,
    accent1Color: _colors.lightBlue500,
    accent2Color: _colors.pinkA400,
    accent3Color: _colors.pinkA100,
    textColor: _colors.fullWhite,
    secondaryTextColor: (0, _colorManipulator.fade)(_colors.fullWhite, 0.7),
    alternateTextColor: '#303030',
    canvasColor: '#303030',
    borderColor: (0, _colorManipulator.fade)(_colors.fullWhite, 0.3),
    disabledColor: (0, _colorManipulator.fade)(_colors.fullWhite, 0.3),
    pickerHeaderColor: (0, _colorManipulator.fade)(_colors.fullWhite, 0.12),
    clockCircleColor: (0, _colorManipulator.fade)(_colors.fullWhite, 0.12)
  }
};

对于 material-ui 版本 1.0.0-beta.36,以下对我有用:

<Tabs indicatorColor={'HEX_COLOR'}>

inkBarStyle 必须在 v1.0

中由 indicatorColor deprecated/replaced

编辑:Link 到 v1.0 文档:https://material-ui-next.com/api/tabs/

编辑:随着 v1.0 的稳定发布,之前的解决方案似乎不再有效。

以下是剩余的解决方案:

  1. indicator class 使用 classes 覆盖。 Link to docs on overrides. Link to docs Tab component with CSS API classes at bottom.
  2. 通过 primarysecondary 颜色意图配置您的主题调色板以使用您想要的颜色。然后您可以指定您想要的 primarysecondary 颜色以与上述 indicatorColor 属性一起使用。 Link to Docs.

类 覆盖可能是更简单的选择。您需要使用 withStyles 组件来注入您的自定义样式 classes。原因是库的样式将覆盖您的 classes 或 styled-components。上面链接的文档提供了一个很好的例子。

@Risa 的解决方案工作得很好,应该是公认的答案。她的解释示例如下所示:

<Tabs
  fullWidth
  centered
  classes={{
    indicator: classes.indicator
  }}>
    <Tab />
    <Tab />
</Tabs>

和样式:

const styles = theme => ({
  indicator: {
    backgroundColor: 'white',
  },
})

你可以试试这个material UI最新版本支持TabIndicatorProps,你可以通过它传递样式键。

<Tabs TabIndicatorProps={{style: {background:'ANY_COLOR'}}}>......

刚刚遇到这个问题,希望对大家有所帮助;

          <Tabs classes={{ indicator: `your classes like underline` }} >
            <Tab
              classes={{ selected: `your classes like underline` }}
            />
            <Tab
              classes={{ selected: classes.selectedTab }}
            />
          </Tabs>

我在这里放了 2019 年末的更新,因为我没有在这里找到我的答案。很多答案都贬值了。

最好的重写方法似乎是使用 material-ui.

的 makeStyle 和 withStyles

这是一个带有制表符的示例。

您需要导入 makeStyles

    import { makeStyles } from '@material-ui/core/styles'
    import Tabs from '@material-ui/core/Tabs'

这是我的习惯 类 使用 makeStyles()

     const useStyles = makeStyles((theme) => ({
     customOne: {
        padding: '3rem 15rem',
        flexGrow: 1,
        backgroundColor: theme.palette.background.paper,
        fontFamily: 'Open Sans',
     },
     customTwo: {
        padding: '0rem',
        color: '#484848',
        backgroundColor: 'white',
        fontFamily: 'Open Sans',
        fontSize: '1rem',
    },
   }))

对于更多覆盖,您还可以使用 withStyles() 创建一个使用道具的函数 material ui(root 等):

    const TabStyle = withStyles((theme) => ({
    root: {
       padding: '1rem 0',
       textTransform: 'none',
       fontWeight: theme.typography.fontWeightRegular,
       fontSize: '1.2rem',
       fontFamily: [
           '-apple-system',
           'BlinkMacSystemFont',
           'Roboto',
       ].join(','),
       '&:hover': {
          backgroundColor: '#004C9B',
          color: 'white',
          opacity: 1,
       },
      '&$selected': {
          backgroundColor: '#004C9B',
          color: 'white',
          fontWeight: theme.typography.fontWeightMedium,
      },
  },
  tab: {
      padding: '0.5rem',
      fontFamily: 'Open Sans',
      fontSize: '2rem',
      backgroundColor: 'grey',
      color: 'black',
      '&:hover': {
          backgroundColor: 'red',
          color: 'white',
          opacity: 1,
      },
  },
  selected: {},
  }))((props) => <Tab {...props} />)

在我的组件中我定义:const 类 = useStyles() 允许在 类.

中更改我的 useStyles 道具

我会像这样随时使用我的习惯 类: 类名={classes.customOne}

    export default function TabsCustom({ activeTabIndex, onChange, values }) {
    const classes = useStyles()
    const [value, setValue] = React.useState(0)

    const handleChange = (event, newValue) => {
       setValue(newValue)
  }


    return (
        <div className={classes.customOne}>
            <Tabs
                className={classes.customTwo}
                variant="fullWidth"
                value={activeTabIndex}
                onChange={onChange}
                aria-label="tabs"
            >
                <TabStyle
                    value="updateDate"
                    icon={(<Icon>insert_invitation</Icon>)}
                    label={i18n.perYear}
                />

            </Tabs>
    </div>
   )
 }

希望对您有所帮助。如果我找到这个解释,我个人会获得很多时间(和痛苦)。

例一:

Js:

<Tabs indicatorColor="primary" classes={{ indicator: classes.indicator }}>

风格:

indicator:{
      backgroundColor: 'green'
    }

例二:

<Tabs TabIndicatorProps={{style: {background:'green'}}} >                    

您现在可以使用 TabIndicatorProps 为当前版本的 MUI (4.10.02) 设置活动指示器的样式。可用文档 here.

有两种方法可以做到这一点:

方法 1:使用样式

import React from "react";
import PropTypes from "prop-types";
import { Tabs, Tab, makeStyles } from "@material-ui/core";

const TabsIndicator = () => {
  const [value, setValue] = React.useState(0);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  return (
    <React.Fragment>
       <Tabs
         value={value}
         onChange={handleChange}
         TabIndicatorProps={{
           style: { background: "cyan", height: "10px", top: "35px" }
         }}
       >
         <Tab label="TEST1" value={0} />
         <Tab label="TEST2" value={1} />
         <Tab label="TEST3" value={2} />
         <Tab label="TEST4" value={3} />
       </Tabs>
    </React.Fragment>
  );
};

export default TabsIndicator;

方法二:使用类

import React from "react";
import PropTypes from "prop-types";
import { Tabs, Tab, makeStyles } from "@material-ui/core";

const useStyles = makeStyles(theme => ({
  indicator: {
    backgroundColor: "green",
    height: "10px",
    top: "45px"
  }
}));

const TabsIndicator = () => {
  const classes = useStyles();

  const [value, setValue] = React.useState(0);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  return (
    <React.Fragment>
        <Tabs
          value={value}
          onChange={handleChange}
          TabIndicatorProps={{ className: classes.indicator }}
        >
          <Tab label="TEST1" value={0} />
          <Tab label="TEST2" value={1} />
          <Tab label="TEST3" value={2} />
          <Tab label="TEST4" value={3} />
        </Tabs>
    </React.Fragment>
  );
};

export default TabsIndicator;

你也可以看看我的sandbox here。希望这对您有所帮助!

嗨,如果有人在更改颜色方面仍有问题,以下对我有用

<Tabs
value={value}
onChange={this.handleChange}
TabIndicatorProps={{
style: {
  backgroundColor: "#D97D54"
 }
}}
>
...
</Tabs>

如果要从 Material UI.

切换颜色,可以使用 TabsindicatorColortextColor 属性
<Tabs
   value={selectedTab}
   indicatorColor="secondary"
   textColor="secondary"
   className="w-full h-64"
>
 ...
</Tabs>

自 2021 年和版本 4.11.1 起,您可以这样做:

import Tabs from '@material-ui/core/Tabs';
import { withStyles } from '@material-ui/core/styles';

const StyledTabs = withStyles({
  indicator: {
    backgroundColor: 'orange'
  }
})(Tabs);

然后使用 StyledTabs,而不是 Tabs。

Link 到文档:

https://material-ui.com/api/tabs/#css

https://material-ui.com/customization/components/#shorthand

MUI v5 更新

您可以在 MUI v5 中使用 sx 属性而不是内联样式。要声明自定义颜色:

<Tabs
  {...}
  TabIndicatorProps={{
    sx: {
      backgroundColor: 'red',
    },
  }}
>

许多 sx 属性也是 theme aware。要使用调色板中的一种颜色:

<Tabs
  {...}
  TabIndicatorProps={{
    sx: {
      backgroundColor: 'secondary.main',
    },
  }}
>

或者如果您想全局更改指示器颜色:

const theme = createTheme({
  components: {
    MuiTabs: {
      styleOverrides: {
        indicator: {
          backgroundColor: 'orange',
          height: 3,
        },
      },
    },
  },
});

现场演示

试试这个

import { makeStyles} from '@mui/styles';

    const useStyles = makeStyles({
  tabs: {

    "& .MuiTabs-indicator": {
      backgroundColor: "orange",
      height: 3,
    },
    "& .MuiTab-root.Mui-selected": {
      color: 'red'
    }
  }
})

然后

const classes = useStyles();
<Tabs
    value={value}
    onChange={handleChange}
    // textColor="secondary"
    // indicatorColor="secondary"
    aria-label="secondary tabs example"
    className={classes.tabs}
    // TabIndicatorProps={{
    //   style: { background: "green", height: 3}
    // }}
  >
  <Tab label={<span className={styles.tabs}>{ABOUT_US}</span>} component={Link} to="/about-us" />
  <Tab label={<span className={styles.tabs}>{ABOUT_HANBANABORINA}</span>} component={Link} to="/about-hanbanaborina" />
  <Tab label={<span className={styles.tabs}>{DOWNLOAD_APPLICATION}</span>} component={Link} to="/download" />
  <Tab label={<span className={styles.tabs}>{HOME}</span>} component={Link} to="/" />
  </Tabs>

MUI v5.2.0

由于 Tabs 组件的道具在 TabList 上也可用,我们可以将 TabIndicatorPropsTabListsx 道具一起用于样式化

<TabList TabIndicatorProps={{ sx: { backgroundColor: 'green'} }} >
  • sx 属性是定义可访问主题的自定义样式的快捷方式。