【问题标题】:How can I change the checkbox styles and icons when hover on it in Material-UI React?在 Material-UI React 中将鼠标悬停在复选框上时如何更改复选框样式和图标?
【发布时间】:2020-06-30 21:24:10
【问题描述】:

我在我的项目中使用 material-ui,并且我有一个红色的复选框。

当有人将鼠标悬停在复选框上时,我想显示选中的图标。

不悬停时会隐藏。我似乎没有找到合适的选择器。我很想得到任何关于我能做些什么的建议。

【问题讨论】:

    标签: javascript html css reactjs material-ui


    【解决方案1】:

    一些注意点:

    • 使用 Material-UI nesting selector 捕获 SVG 元素,因为 <Checkbox /> 是一个具有静态 dom 结构的 lib 元素。

    • 使用&:hover 捕捉onMouseOver 事件。

    • 使用d: path(value) 将props d 的值传递给SVG 的子元素<path />

    import React from "react";
    import "./styles.css";
    import { Checkbox } from "@material-ui/core";
    import { makeStyles } from "@material-ui/core/styles";
    import AcUnit from "@material-ui/icons/AcUnit";
    // import Accessibility from "@material-ui/icons/Accessibility";
    
    const useStyles = makeStyles(theme => ({
      root: {
        background: "#f1f1f1",
        "&:hover": {
          "& span": {
            "& svg": {
              "& path": {
                d:
                  "path('M12 2c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm9 7h-6v13h-2v-6h-2v6H9V9H3V7h18v2z')"
              }
            }
          }
        }
      }
    }));
    
    export default function App() {
      const classes = useStyles();
      return (
        <div className="App">
          <Checkbox className={classes.root} icon={<AcUnit />} />
        </div>
      );
    }
    

    在线试用:


    参考:浏览器中可以看到的&lt;Checkbox /&gt;结构

    <span
      class="MuiButtonBase-root MuiIconButton-root PrivateSwitchBase-root-8 MuiCheckbox-root MuiCheckbox-colorSecondary makeStyles-root-85 MuiIconButton-colorSecondary"
      aria-disabled="false"
    >
      <span class="MuiIconButton-label">
        <input
          class="PrivateSwitchBase-input-11"
          type="checkbox"
          data-indeterminate="false"
          value=""
        /><svg
          class="MuiSvgIcon-root"
          focusable="false"
          viewBox="0 0 24 24"
          aria-hidden="true"
          role="presentation"
        >
          <path
            d="M22 11h-4.17l3.24-3.24-1.41-1.42L15 11h-2V9l4.66-4.66-1.42-1.41L13 6.17V2h-2v4.17L7.76 2.93 6.34 4.34 11 9v2H9L4.34 6.34 2.93 7.76 6.17 11H2v2h4.17l-3.24 3.24 1.41 1.42L9 13h2v2l-4.66 4.66 1.42 1.41L11 17.83V22h2v-4.17l3.24 3.24 1.42-1.41L13 15v-2h2l4.66 4.66 1.41-1.42L17.83 13H22z"
          ></path>
        </svg>
      </span>
      <span class="MuiTouchRipple-root"></span>
    </span>
    

    【讨论】:

    • 谢谢!奇迹般有效。我想知道改变 svg 的路径,但不知道该怎么做。你的解决方案教会了我很多。再次感谢您
    猜你喜欢
    • 2023-01-19
    • 2019-11-13
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 2020-07-01
    相关资源
    最近更新 更多