简体   繁体   English

如何更改 hover 上的图标颜色?

[英]How to change icon color on hover?

I'm trying to change the color of a material icon inside IconButton material component (an action that should trigger color change - hover over IconButton ).我正在尝试更改IconButton材质组件内的材质图标的颜色(应该触发颜色更改的操作 - hover over IconButton )。

How this could be done?如何做到这一点? Adding class to the icon directly works only if hover over icon itself and not over IconButton .仅当 hover 超过图标本身而不是IconButton时,将 class 直接添加到图标才有效。

My code:我的代码:

<IconButton className="add-icon-btn" onClick={toggleNominationForm}>
  {!showForm ? <AddBoxIcon /> : <IndeterminateCheckBoxIcon /> }
</IconButton>

在此处输入图像描述

Here you have a full example, I hope this solves your problem:在这里你有一个完整的例子,我希望这能解决你的问题:

import React from 'react'
import { makeStyles } from '@material-ui/styles'
import IconButton from '@material-ui/core/IconButton'
import AddBoxIcon from '@material-ui/icons/AddBox'
import IndeterminateCheckBoxIcon from '@material-ui/icons/IndeterminateCheckBox'

export default () => {

    const [showForm, setShowForm] = React.useState(false)
    const classes = useClasses()

    return (
        <IconButton
            classes={{
                root: classes.iconContainer
            }}
        >
            {!showForm
                ? <AddBoxIcon className={classes.icon}/>
                : <IndeterminateCheckBoxIcon className={classes.icon}/>
            }
        </IconButton>
    )
}

const useClasses = makeStyles(theme => ({
    iconContainer: {
        "&:hover $icon": {
            color: 'red',
        }
    },
    icon: {
        color: 'blue',
    },
}))

You can use following property您可以使用以下属性

sx={{ "&:hover": { color: "blue" } }}
<IconButton
              size="large"
              aria-label="show 17 new notifications"
              color="inherit"
              sx={{ "&:hover": { color: "blue" } }}
            >
              <Badge badgeContent={17} color="primary">
                <LayersIcon />
              </Badge>
            </IconButton>

You need a hover state probably.您可能需要一个hover state。 So, you can use onMouseEnter and onMouseLeave for the outer icon and then set the style by using this condition for the inner icon.因此,您可以将onMouseEnteronMouseLeave用于外部图标,然后使用此条件为内部图标设置样式。 This logic is borrowed from this answer .这个逻辑是从这个答案中借来的。 So, I'm setting my answer as CW.所以,我将我的答案设置为 CW。

<IconButton
  onMouseEnter={() => {
    setHover(true);
  }}
  onMouseLeave={() => {
    setHover(false);
  }}
  className="add-icon-btn"
  onClick={toggleNominationForm}
>
  {!showForm ? (
    <AddBoxIcon style={{ backgroundColor: hover ? "blue" : "yellow" }} />
  ) : (
    <IndeterminateCheckBoxIcon />
  )}
</IconButton>

Try adding the following CSS -尝试添加以下 CSS -

.IconButton:hover .Iconclass {
  background-color: /*desired color*/;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM