Material-UI: 类 不能使用外部 SVG 图标?

Material-UI: classes isn't working with external SVG icons?

我创建了一个 Material-UI 永久抽屉,其中有一个列表项组件,旨在在用户单击列表项时更改图标颜色。但是我的样式只适用于 Material-UI 图标,不适用于外部 SVG。

这里是codesandboxlink同一个项目,方便理解

这是呈现我的 listItem 组件的 AppBarDrawer.js 父组件。工作正常,可以忽略

import React from "react";
import clsx from "clsx";
import { makeStyles, useTheme } from "@material-ui/core/styles";
import Drawer from "@material-ui/core/Drawer";
import CssBaseline from "@material-ui/core/CssBaseline";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import List from "@material-ui/core/List";
import Typography from "@material-ui/core/Typography";
import Divider from "@material-ui/core/Divider";
import IconButton from "@material-ui/core/IconButton";
import MenuIcon from "@material-ui/icons/Menu";
import ChevronLeftIcon from "@material-ui/icons/ChevronLeft";
import ChevronRightIcon from "@material-ui/icons/ChevronRight";
import ListItem from "@material-ui/core/ListItem";
import ListItemIcon from "@material-ui/core/ListItemIcon";
import ListItemText from "@material-ui/core/ListItemText";
import InboxIcon from "@material-ui/icons/MoveToInbox";
import MailIcon from "@material-ui/icons/Mail";
import DrawerList from "./components/DrawerList";

const drawerWidth = 240;

const useStyles = makeStyles((theme) => ({
  root: {
    display: "flex"
  },
  appBar: {
    transition: theme.transitions.create(["margin", "width"], {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen
    })
  },
  appBarShift: {
    width: `calc(100% - ${drawerWidth}px)`,
    marginLeft: drawerWidth,
    transition: theme.transitions.create(["margin", "width"], {
      easing: theme.transitions.easing.easeOut,
      duration: theme.transitions.duration.enteringScreen
    })
  },
  menuButton: {
    marginRight: theme.spacing(2)
  },
  hide: {
    display: "none"
  },
  drawer: {
    width: drawerWidth,
    flexShrink: 0
  },
  drawerPaper: {
    width: drawerWidth
  },
  drawerHeader: {
    display: "flex",
    alignItems: "center",
    padding: theme.spacing(0, 1),
    // necessary for content to be below app bar
    ...theme.mixins.toolbar,
    justifyContent: "flex-end"
  },
  content: {
    flexGrow: 1,
    padding: theme.spacing(3),
    transition: theme.transitions.create("margin", {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen
    }),
    marginLeft: -drawerWidth
  },
  contentShift: {
    transition: theme.transitions.create("margin", {
      easing: theme.transitions.easing.easeOut,
      duration: theme.transitions.duration.enteringScreen
    }),
    marginLeft: 0
  }
}));

export default function PersistentDrawerLeft() {
  const classes = useStyles();
  const theme = useTheme();
  const [open, setOpen] = React.useState(true);

  const handleDrawerOpen = () => {
    setOpen(true);
  };

  const handleDrawerClose = () => {
    setOpen(false);
  };

  return (
    <div className={classes.root}>
      <CssBaseline />
      <AppBar
        position="fixed"
        className={clsx(classes.appBar, {
          [classes.appBarShift]: open
        })}
      >
        <Toolbar>
          <IconButton
            color="inherit"
            aria-label="open drawer"
            onClick={handleDrawerOpen}
            edge="start"
            className={clsx(classes.menuButton, open && classes.hide)}
          >
            <MenuIcon />
          </IconButton>
          <Typography variant="h6" noWrap>
            Persistent drawer
          </Typography>
        </Toolbar>
      </AppBar>
      <Drawer
        className={classes.drawer}
        variant="persistent"
        anchor="left"
        open={open}
        classes={{
          paper: classes.drawerPaper
        }}
      >
        <div className={classes.drawerHeader}>
          <IconButton onClick={handleDrawerClose}>
            {theme.direction === "ltr" ? (
              <ChevronLeftIcon />
            ) : (
              <ChevronRightIcon />
            )}
          </IconButton>
        </div>
        <Divider />
        <List>
          <DrawerList />
        </List>
      </Drawer>
      <main
        className={clsx(classes.content, {
          [classes.contentShift]: open
        })}
      >
        <div className={classes.drawerHeader} />

        <Typography paragraph>
          Lorem Nulla posuere sollicitudin aliquam ultrices sagittis orci a
        </Typography>
      </main>
    </div>
  );
}

主文件 DrawerList.js 未给出所需的输出

这里真正的问题是我的外部图标颜色在我点击它时没有变成白色但是最后一个名为 ExitToAppOutlined 的图标是 Material-UI 图标并且是点击时工作正常。

import React, { useState } from "react";
import ListItem from "@material-ui/core/ListItem";
import Link from "@material-ui/core/Link";
import ListItemIcon from "@material-ui/core/ListItemIcon";
import { ExitToAppOutlined } from "@material-ui/icons";
import ListItemText from "@material-ui/core/ListItemText";
import { useStyles } from "./DrawerListStyle";
import Typography from "@material-ui/core/Typography";
import Box from "@material-ui/core/Box";
import { SvgIcon } from "@material-ui/core";

import { ReactComponent as Appointment } from "../../assets/Appointment.svg";
import { ReactComponent as Customers } from "../../assets/manage customers 2.svg";

const itemList = [
  {
    text: "Book Appointment",
    icon: (
      <SvgIcon>
        {/* external icons as svg */}
        <Appointment />
      </SvgIcon>
    )
  },
  {
    text: "Manage",
    icon: (
      <SvgIcon>
        {/* external icons as svg */}
        <Customers />
      </SvgIcon>
    )
  },
  {
    text: "Logout",
    // Material Icons
    icon: <ExitToAppOutlined />
  }
];

const DrawerList = () => {
  const [selectedIndex, setSelectedIndex] = useState(0);
  const classes = useStyles();

  const ListData = () =>
    itemList.map((item, index) => {
      const { text, icon } = item;

      return (
        <ListItem
          button
          key={text}
          component={Link}
          selected={index === selectedIndex}
          onClick={(e) => handleListItemClick(e, index)}
          style={selectedIndex === index ? { backgroundColor: "#6A2CD8" } : {}}
        >
          <ListItemIcon
            className={classes.iconStyle}
            style={selectedIndex === index ? { color: "#fff" } : {}}
          >
            {icon}
            <ListItemText>
              <Typography
                component="div"
                className={classes.iconTitle}
                style={selectedIndex === index ? { color: "#fff" } : {}}
              >
                <Box fontWeight={500} fontSize={13.5}>
                  {text}
                </Box>
              </Typography>
            </ListItemText>
          </ListItemIcon>
        </ListItem>
      );
    });
  const handleListItemClick = (e, index) => {
    setSelectedIndex(index);
  };

  return (
    <div className={classes.root}>
      <ListData />
    </div>
  );
};

export default DrawerList;

DrawerListStyle.js 只是一个 stylejs 文件,可以忽略

import { makeStyles } from "@material-ui/core";

const useStyles = makeStyles((theme) => ({
  root: {
    marginTop: theme.spacing(2)
  },
  iconStyle: {
    margin: theme.spacing(0, 0, 1, 0),
    color: "#6A2CD8"
  },
  iconTitle: {
    margin: theme.spacing(0, 0, 0, 1),
    color: "#555458"
  }
}));

export { useStyles };

Material-UI 在选择 ListItem 时设置 ListItemIconcolor,但是因为您的自定义 svg 图标已经将 fill 属性设置为另一种颜色,它会覆盖 MUI 中的 color。修复很简单,使用 makeStyles:

在自定义 svg 中再次覆盖 fill 属性
const useStyles = makeStyles((theme) => ({
  {...}
  listItem: {
    "&.Mui-selected": {
      "& path": {
        fill: "white"
      }
    }
  }
}));
<ListItem className={classes.listItem}

现场演示