在 MUI 中设置 Snackbar 的背景颜色

Set the background color of a Snackbar in MUI

我正在使用 MUI 的 Snackbar 组件。目前 Snackbar 显示为黑色。你知道我怎样才能改变颜色吗?设置 background-color 只会改变 Snackbar 所在的整个 div 的颜色。它不会改变 Snackbar.

的颜色

您必须设置 bodyStyle 属性:

<Snackbar bodyStyle={{ backgroundColor: 'teal', color: 'coral' }} />

您可以在 documentation

中找到有关如何自定义小吃店的更多信息

使用 material-ui 1.0(或更高版本),您应该使用属性 ContentProps 覆盖 SnackbarContent 组件中的根 CSS class .

这是一个例子:

const styles = {
  root: {
    background: 'red'
  }
};

class MySnackbar extends Component {
  render() {
    const { classes } = this.props;

    return (
      <Snackbar
        ContentProps={{
          classes: {
            root: classes.root
          }
        }}
        message={<span>Some message</span>}
      />
    );
  }
}

export default withStyles(styles)(MySnackbar);

如果有人不想将样式作为道具传递,我们也可以在css文件中写一个class并将其分配给ContentProps,像这样:

ContentProps={{
  classes: {
    root: 'errorClass'
  }
}}

并在 index.css 文件中:

.errorClass { color: 'red' }

在当前的 material-ui 版本 (4.3.0) 中,有一种比 ContentProps 方法更简单的方法。您可以使用 SnackbarContent 作为子属性,而不是 message 属性,只需在其上调用 style={}

<Snackbar
  open={this.state.showSnackbar}
  autoHideDuration={3000}
  onClose={() => {this.setState({showSnackbar: false})}}
>
  <SnackbarContent style={{
      backgroundColor:'teal',
    }}
    message={<span id="client-snackbar">Hello World</span>}
  />
</Snackbar>

Snackbar 的根组件只关心正确定位自身,如果你想改变物理 Snackbar 的外观,你需要通过 SnackbarContent 定位 SnackbarContent =17=] 道具。在 v5 中,您可以使用 sx 轻松做到这一点:

<Snackbar
  ContentProps={{
    sx: {
      background: "red"
    }
  }}

另一种方法是为您的 Snackbar 创建一个 custom variant:

import { createTheme, ThemeProvider } from "@mui/material/styles";

const theme = createTheme({
  components: {
    MuiSnackbar: {
      variants: [
        {
          props: { variant: "trouble" },
          style: {
            "& .MuiSnackbarContent-root": {
              background: "orange"
            }
          }
        },
        {
          props: { variant: "bigTrouble" },
          style: {
            "& .MuiSnackbarContent-root": {
              background: "red"
            }
          }
        }
      ]
    }
  }
});
<Snackbar variant="bigTrouble"

要与 typescript 一起使用,您还需要更新 Snackbar 的属性类型:

declare module "@mui/material/Snackbar" {
  interface SnackbarProps {
    variant: "trouble" | "bigTrouble";
  }
}

使用 MUI v5 自定义 Snackbar(背景、文本颜色或任何其他样式)的最佳选择是使用 sx prop 和变体的特定类名:

<Snackbar
  sx={{
    '& .SnackbarItem-variantSuccess': {
      backgroundColor: colors.primary, //your custom color here
    },
    '& .SnackbarItem-variantError': {
      backgroundColor: colors.alert, //your custom color here
    },
    '& .SnackbarItem-variantWarning': {
      backgroundColor: colors.attention, //your custom color here
    },
    '& .SnackbarItem-variantInfo': {
      backgroundColor: colors.secondary, //your custom color here
    },
  }}
  autoHideDuration={10000}
  //...other props here>
</Snackbar>

可以将相同的方法应用于 notistack 库来自定义他们的 snackbar。