首页 > 解决方案 > 徽章组件的自定义颜色不起作用

问题描述

我需要为我的Badge组件添加自定义颜色,但它似乎不起作用。

我试过这些:

<Badge className="badge" badgeStyle={{backgroundColor: '#00AFD7'}} variant="dot" />

<Badge className="badge" color='#00AFD7' variant="dot" />

这些不起作用。如何将自定义颜色传递给我的Badge组件

标签: reactjsmaterial-ui

解决方案


您可以利用withStyles和使用badge css 类来自定义它。

这是一个例子:

import React from "react";
import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";
import Badge from "@material-ui/core/Badge";
import MailIcon from "@material-ui/icons/Mail";

const styles = theme => ({
  margin: {
    margin: theme.spacing.unit * 2
  },
  customBadge: {
    backgroundColor: "#00AFD7",
    color: "white"
  }
});

function SimpleBadge(props) {
  const { classes } = props;
  return (
    <div>
      <Badge
        classes={{ badge: classes.customBadge }}
        className={classes.margin}
        badgeContent={10}
      >
        <MailIcon />
      </Badge>
    </div>
  );
}

SimpleBadge.propTypes = {
  classes: PropTypes.object.isRequired
};

export default withStyles(styles)(SimpleBadge);

编辑徽章自定义颜色

在 v4 中,您可以在利用 props 的样式中使用函数。

此处的文档:https ://material-ui.com/styles/basics/#adapting-the-higher-order-component-api

const styles = theme => ({
  margin: {
    margin: theme.spacing.unit * 2
  },
  customBadge: {
    backgroundColor: props => props.color,
    color: "white"
  }
});

编辑徽章自定义颜色


推荐阅读