如何在Material UI Chip组件

时间:2017-12-14 15:39:55

标签: reactjs material-ui

我的芯片实现了多种颜色(绿色,黄色,蓝色等),默认情况下MUI Chip带有灰色悬停/主动/焦点CSS样式。我需要在MUI芯片组件中消除这种悬停/活动/聚焦灰色背景颜色。所以我再次想要用另一种颜色替换灰色,但要完全消除以下CSS样式:

clickable: {
  // Remove grey highlight
  WebkitTapHighlightColor: theme.palette.common.transparent,
  cursor: 'pointer',
  '&:hover, &:focus': {
    backgroundColor: emphasize(backgroundColor, 0.08),
  },
  '&:active': {
    boxShadow: theme.shadows[1],
    backgroundColor: emphasize(backgroundColor, 0.12),
  },
},
deletable: {
  '&:focus': {
    backgroundColor: emphasize(backgroundColor, 0.08),
  },
},

最后,这可以通过覆盖所需颜色的芯片组件来完成,但必须有更好的方法。

1 个答案:

答案 0 :(得分:7)

您可以创建一个工厂函数,该函数返回具有您选择颜色的组件,并覆盖您问题中突出显示的行为:

import React from 'react';
import { withStyles } from 'material-ui/styles';
import Chip from 'material-ui/Chip';
import { emphasize, fade } from 'material-ui/styles/colorManipulator';

const ChipFactory = (color = null, deleteIconColor = null) => {
  const styles = theme => {
    const backgroundColor = emphasize(color || theme.palette.background.default, 0.12);
    const deleteIconColor = fade(deleteIconColor || theme.palette.text.primary, 0.26);
    return {
      root: {
        color: theme.palette.getContrastText(backgroundColor),
        backgroundColor,
      },
      clickable: {
        cursor: 'pointer',
        '&:hover, &:focus': {
          backgroundColor: emphasize(backgroundColor, 0.08),
        },
        '&:active': {
          backgroundColor: emphasize(backgroundColor, 0.12),
        },
      },
      deletable: {
        '&:focus': {
          backgroundColor: emphasize(backgroundColor, 0.08),
        },
      },
      deleteIcon: {
        color: deleteIconColor,
        '&:hover': {
          color: fade(deleteIconColor, 0.4),
        },
      },
    };
  };

  const CustomChip = ({ classes, ...props }) =>
    <Chip classes={classes} {...props} />;

  return withStyles(styles)(CustomChip);
};

export default ChipFactory;

您可以通过调用此函数动态生成新的变体,而不是为每种颜色创建单独的组件:

// excerpt from Chips demo
render() {
  const { classes } = props;

  const GreenChip = ChipFactory('#0f0');
  const RedChip = ChipFactory('#f00');
  const BlueChip = ChipFactory('#00f');

  return (
    <div className={classes.row}>
      <GreenChip label="Basic Chip" className={classes.chip} />
      <RedChip
        avatar={<Avatar>MB</Avatar>}
        label="Clickable Chip"
        onClick={handleClick}
        className={classes.chip}
      />
      <BlueChip
        avatar={<Avatar src="/static/images/uxceo-128.jpg" />}
        label="Deletable Chip"
        onRequestDelete={handleRequestDelete}
        className={classes.chip}
      />
    </div>
  );
}

有关正常工作的版本,请参阅此code sandbox