【问题标题】:Overriding MUI Chip deleteIcon color覆盖 MUI 芯片 deleteIcon 颜色
【发布时间】:2023-04-08 00:30:01
【问题描述】:

我正在尝试为 Chip 组件 (MUI v5) 的 deleteIcon 提供自定义颜色。如我所见,我的样式被.css-inlzrk-MuiButtonBase-root-MuiChip-root .MuiChip-deleteIcon 覆盖,但我无法覆盖它。我不想提供内联样式(例如<Cancel style={{color: 'blue'}} />)。

import * as React from "react";
import Chip from "@mui/material/Chip";
import Stack from "@mui/material/Stack";
import { makeStyles } from "@mui/styles";

import Cancel from "@mui/icons-material/Cancel";

export default function DeleteableChips() {
  const classes = makeStyles((theme) => ({
    icon: {
      color: "blue"
    }
  }))();

  const handleDelete = () => {
    console.info("You clicked the delete icon.");
  };

  return (
    <Stack direction="row" spacing={1}>
      <Chip
        className={{ deleteIcon: classes.deleteIcon }}
        label="Deletable"
        onDelete={handleDelete}
        deleteIcon={<Cancel className={classes.icon} />}
      />
      <Cancel className={classes.icon} />
    </Stack>
  );
}

代码沙盒: https://codesandbox.io/s/deleteablechips-material-demo-forked-d6jq5?file=/demo.js

【问题讨论】:

  • 演示目前已损坏 (Could not find dependency: '@mui/styles')。您可以尝试修复它以便更容易复制吗?谢谢!
  • 我想我忘了保存 package.json。我可以再试一次吗?
  • 酷,它现在可以工作了
  • 芯片内部的图标不是蓝色的...或者它对您有用吗?您的浏览器上的两个取消图标都是蓝色的吗?
  • 我明白了。没关系,我似乎没有完全理解这个问题

标签: reactjs material-ui jss


【解决方案1】:

您不应使用 makeStyles 或 v5 中 @mui/styles 包中的任何内容。来自docs

@mui/styles 是 MUI 的传统样式解决方案。它在 v5 中已弃用。它依赖于 JSS 作为样式解决方案,@mui/material 中不再使用它。如果您不想在捆绑包中同时包含情感和 JSS,请参阅@mui/system 文档,这是推荐的替代方法。

替代方案是sx prop/styled()。以下是其中的 2 个示例:

sx道具

<Chip
  sx={{
    '& .MuiChip-deleteIcon': {
      color: 'red',
    },
  }}
  label="Deletable"
  onDelete={() => {}}
/>

styled()

const options = {
  shouldForwardProp: (prop) => prop !== 'deleteIconColor',
};
const StyledChip = styled(
  Chip,
  options,
)(({ deleteIconColor }) => ({
  '& .MuiChip-deleteIcon': {
    color: deleteIconColor,
  },
}));
<StyledChip
  label="Deletable"
  onDelete={() => {}}
  deleteIconColor="orange"
/>

【讨论】:

  • 谢谢!我正在将 Hustle 从 v4 升级到 v5。来自文档的非常好的见解。
【解决方案2】:

编辑:您可以覆盖类deleteIcon

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    deleteIcon: {
      color: "red"
    }
  })
);
      <Chip
        classes={{ deleteIcon: classes.deleteIcon }}
        label="Deletable"
        onDelete={handleDelete}
      />

查看此示例:https://codesandbox.io/s/material-demo-forked-x2dx7?file=/demo.tsx

【讨论】:

  • 为什么?与className 没有区别:codesandbox.io/s/…
  • @EliranMalka 没有显示给我,你指的是芯片里面的图标吗
  • 它对我不起作用:codesandbox.io/s/…我错过了什么吗?
  • @Kerematam 我已经更新了我的示例,也许会有用
【解决方案3】:

你可以这样做。

const classes = makeStyles((theme) => ({
    icon: {
      "&.MuiChip-deleteIcon": {
        color: "blue"
      }
    }
}))();

您可以查看 this sandbox 以获取此用法的实时工作示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-26
    • 2021-12-07
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 2018-07-28
    • 2021-10-21
    相关资源
    最近更新 更多