如何设置 MuiButton 文本和活动颜色

IT技术 reactjs material-ui
2021-05-17 06:19:09

我正在创建一个 Material-UI 主题:

export const theme = createMuiTheme({
  palette: {
    primary: {
      main: '#7ab800',
      dark: '#34b233',
    },
  })

这给了我一个默认main颜色的按钮,活动背景是dark绿色:

在此处输入图片说明

但是我希望文本是白色的。如果我contrastTextprimary属性中定义

export const theme = createMuiTheme({
  palette: {
    primary: {
      main: '#7ab800',
      dark: '#34b233',
      contrastText: 'white',
    },
  })

处于活动状态时,活动背景现在比main...

在此处输入图片说明

1个回答

您所指的“活动”背景是由 Button 的TouchRipple效果引起的您可以在TouchRipple源代码中找到它的样式

  /* Styles applied to the internal `Ripple` components `child` class. */
  child: {
    opacity: 1,
    display: 'block',
    width: '100%',
    height: '100%',
    borderRadius: '50%',
    backgroundColor: 'currentColor',
  }

请注意,backgroundColor波纹的 'currentColor'。因此,当文本颜色为黑色时,波纹的背景颜色为黑色;当文本颜色为白色时,波纹的背景颜色为白色。这有助于确保波纹对按钮产生可见效果——黑色背景按钮上的黑色波纹不会出现,但当前颜色应始终与背景形成对比。

与 Material-UI 中的几乎所有样式一样,您当然可以在知道如何进行自定义后进行自定义。在下面的示例代码中,您可以看到如何在主题中使用overrides: { MuiTouchRipple: {...} }或在单个按钮上使用TouchRipplePropsprops中传入child来覆盖它classes

import React from "react";
import ReactDOM from "react-dom";
import {
  createMuiTheme,
  MuiThemeProvider,
  withStyles
} from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
const theme1 = createMuiTheme({
  palette: {
    primary: {
      main: "#7ab800",
      dark: "#34b233"
    }
  }
});
console.log(theme1);
const theme2 = createMuiTheme({
  palette: {
    primary: {
      main: "#7ab800",
      dark: "#34b233",
      contrastText: "white"
    }
  }
});
const theme3 = createMuiTheme({
  palette: {
    primary: {
      main: "#7ab800",
      dark: "#34b233",
      contrastText: "white"
    }
  },
  overrides: {
    MuiTouchRipple: {
      child: {
        backgroundColor: "rgba(0, 0, 0, 0.87)"
      }
    }
  }
});
const styles = {
  child: {
    backgroundColor: "rgba(0, 0, 0, 0.87)"
  }
};

function App({ classes }) {
  return (
    <>
      <MuiThemeProvider theme={theme1}>
        <Button variant="contained" color="primary">
          Theme 1
        </Button>
      </MuiThemeProvider>
      <br />
      <MuiThemeProvider theme={theme2}>
        <Button variant="contained" color="primary">
          Theme 2
        </Button>
        <Button variant="contained" color="primary" disableRipple>
          Theme 2 No Ripple
        </Button>
        <Button
          TouchRippleProps={{ classes: classes }}
          variant="contained"
          color="primary"
        >
          Theme 2 button-specific Ripple Override
        </Button>
      </MuiThemeProvider>
      <br />
      <MuiThemeProvider theme={theme3}>
        <Button variant="contained" color="primary">
          Theme 3 - theme-wide Ripple Override
        </Button>
      </MuiThemeProvider>
    </>
  );
}
const StyledApp = withStyles(styles)(App);
const rootElement = document.getElementById("root");
ReactDOM.render(<StyledApp />, rootElement);

编辑 617pw32323