簡體   English   中英

Material-UI:類不適用於外部 SVG 圖標?

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

我創建了一個 Material-UI 持久抽屜,其中有一個列表項組件,旨在在用戶單擊列表項時更改圖標顏色。 但我的樣式僅適用於 Material-UI 圖標,不適用於外部 SVG。

這是同一項目的代碼框鏈接,可以更好地理解它。

這是呈現我的 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 在選擇ListItemIcon時設置ListItemcolor ,但是因為您的自定義svg圖標已經將fill屬性設置為另一種顏色,它會覆蓋 MUI 中的color 修復很簡單,使用makeStyles在您的自定義 svg 中再次覆蓋fill屬性:

const useStyles = makeStyles((theme) => ({
  {...}
  listItem: {
    "&.Mui-selected": {
      "& path": {
        fill: "white"
      }
    }
  }
}));
<ListItem className={classes.listItem}

現場演示

編輯 67092230/why-material-ui-classes-isnt-working-with-external-svg-icon

您還可以使用SVGR構建自己的圖標。

您可以按照以下步驟操作:

1-使用安裝 svgr

npm install --save-dev @svgr/cli
# or use yarn
yarn add --dev @svgr/cli

2-在public/icons

3-創建一個名為svgr.config.js的文件並將其放在項目的根目錄中

module.exports = {
    icon: true,
    dimensions: false,
    expandProps: false,
    replaceAttrValues: {
        '#000': 'currentColor',
        '#292D32': 'currentColor',
        '#292d32': 'currentColor',
        '#55BB9D': 'currentColor',
        '#FFBC50': 'currentColor',
        '#A7A7A7': 'currentColor'
    }
};

4- 在 package.json "svg": "svgr --ext=jsx -d src/@share/icons public/icons"中添加腳本

5 運行yarn svg

一旦你運行上面的命令 svgr 抓取公共文件夾中的所有圖標,並根據你提供的配置在src/@share/icons文件夾中生成 React 組件。 並將 svg 的每個顏色文本替換為當前顏色。 在這種情況下,將replaceAttrValues中的每個鍵替換為currentColor

然后在您的反應組件中,您可以簡單地執行以下操作:

import { MyIcon } from '@share/icons';
import { SvgIcon } from '@mui/material';

function MyComponent() {
    return <p><SvgIcon component={MyIcon} /> check this icon </p>
};

export default MyComponent;

這樣,您可以像更改p元素的文本顏色一樣更改顏色。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM