如何在主题替代中覆盖材质ui的选定颜色以进行反应

时间:2018-08-21 23:39:07

标签: reactjs tabs override material-ui

我想为material ui for React中的所有标签覆盖选定的文本颜色。我知道我可以使用以下代码覆盖某些部分:

const theme = createMuiTheme({
  overrides: {
    MuiTab: {
      root: {
        color: '#000000',
        backgroundColor: '#ffffff',
        '&:hover': {
          backgroundColor: 'rgba(108, 130, 168, 0.11764705882352941)',
          color: '#000000',
        }
      }
    }
  }
});

之后

 <MuiThemeProvider theme={theme}>
    <HomePage/>
 </MuiThemeProvider>

但是,当选择了选项卡时,它将应用一个类,例如“ .MuiTab-textColorPrimary-144.MuiTab-selected-146”。选择Tab组件时,如何为textColorPrimary指定全局替代颜色?我对全局替代而不是对单个实例替代特别感兴趣。缺少Tab组件的特定方式,如何为“选定的” primaryTextColor指定全局替代?

5 个答案:

答案 0 :(得分:4)

代码:

const theme = createMuiTheme({
  overrides: {
    MuiTabs: {
      indicator: {
        backgroundColor: orange[700]
      }
    },
    MuiTab: {
      root: {
        "&:hover": {
          backgroundColor: pink[100],
          color: pink[700]
        }
      },
      selected: {
        backgroundColor: orange[100],
        color: orange[700],
        "&:hover": {
          backgroundColor: green[100],
          color: green[700]
        }
      }
    }
  }
});

实时示例: https://codesandbox.io/s/mj9x1zy4j9

答案 1 :(得分:1)

为了覆盖 selected 规则,您需要使用 $ruleName 语法。 规则覆盖应该在根定义中: (Forked code sandbox with the fixed syntax)

const theme = createMuiTheme({
  overrides: {
    MuiTabs: {
      indicator: {
        backgroundColor: orange[700]
      }
    },
    MuiTab: {
      root: {
        "&:hover": {
          backgroundColor: pink[100],
          color: pink[700]
        },
        "&$selected": {
          backgroundColor: orange[100],
          color: orange[700],
          "&:hover": {
            backgroundColor: cyan[500],
            color: green[700]
          }
        }
      }
    }
  }
});

答案 2 :(得分:0)

也可以使用TabIndicatorProps

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

如果您需要无指示符

const theme = createMuiTheme({
  overrides: {
    MuiTabs: {
      indicator: {
        backgroundColor: `transparent`
      }
    },

答案 3 :(得分:0)

接受的答案中的CodeSandbox示例在最新版本的MUI(3.9.1)中不再起作用,并且当我尝试通过建议的更改解决问题时,它还会显示另一条错误消息。请参阅下面的屏幕截图。请参阅下面的解决方案。

enter image description here

enter image description here

eps1lon向我展示了如何在此code sandbox上执行此操作。 现在,这应该是公认的答案。

答案 4 :(得分:0)

您应将所选内容插入到根节点中,如下所示:

  const theme = createMuiTheme({
    overrides: {
      MuiTab: {
        root: {
          "&:hover": {
            backgroundColor: pink[100]
          },
          selected: {
            backgroundColor: orange[100]            
          }
        },
      }
    }
});