芯片在悬停时变色

时间:2019-02-06 11:30:45

标签: javascript css material-ui

我在代码上使用了芯片,当鼠标悬停在其上方时,我想更改颜色。我尝试使用

hover:{
            backgroundColor: 'red',
        }

我使用了const StyledChip = withStyles( ...

但是它不起作用!有人能帮我吗?感谢您的建议!

代码类似于

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Avatar from '@material-ui/core/Avatar';
import Chip from '@material-ui/core/Chip';

const styles = theme => ({
  root: {
    display: 'flex',
    justifyContent: 'center',
    flexWrap: 'wrap',
  },
  chip: {
    margin: theme.spacing.unit,
  },
});

const StyledChip = withStyles({
  root: {
    backgroundColor: 'white',
  },
  '&:hover': {
    backgroundColor: 'red',
  }
})(Chip);


function Chips(props) {
  const { classes } = props;
  return (
    <div className={classes.root}>

      <StyledChip
        avatar={
          <Avatar>
            <FaceIcon />
          </Avatar>
        }
        label="Clickable Deletable Chip"
      />
    </div>
  );
}

Chips.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(Chips);

我尝试以其他方式修复它,但不起作用

1 个答案:

答案 0 :(得分:1)

传递给withStyles的对象中的第一级键只是您可以使用的键(在传递给组件的classes属性中),以获取由生成的实际CSS类名称withStyles

因此,当您具有以下条件时:

const StyledChip = withStyles({
  root: {
    backgroundColor: 'white',
  },
  '&:hover': {
    backgroundColor: 'red',
  }
})(Chip);

这意味着Chip可以访问两种不同的类-一种通过props.classes.root可以将背景设置为白色,另一种可以通过props.classes['&:hover']来使用将背景设置为红色。 Chip组件根本不会关注第二个类,因此它没有任何作用。

但是,如果您使用以下语法:

const StyledChip = withStyles({
  root: {
    backgroundColor: "white",
    "&:hover": {
      backgroundColor: "red"
    }
  }
})(Chip);

“&:hover”现在成为root类定义的部分。现在&的意思是“该密钥所属的类”,因此将生成如下CSS:

.root-generated-class-name {
  background-color: white;
}
.root-generated-class-name:hover {
  background-color: red;
}

在此示例中,props.classes.root的值为root-generated-class-name

这是一个可行的示例:

Edit o8vvlzn2z

相关问题