【问题标题】:How to write some text over a MaterialUI-icon如何在 Material UI 图标上写一些文本
【发布时间】:2020-08-28 05:24:26
【问题描述】:

我正在做一个项目,我需要在一个图标上写一个数字。 我正在使用 MaterialUI ModeComment 图标,我想在它上面写一些文字。 我尝试了以下方法,但没有奏效。

<ModeComment color='primary'>
  <Typography>2</Typography>
</ModeComment>
<ModeComment color='primary'>
   <span>2</span>
</ModeComment>

我该怎么做?提前致谢

【问题讨论】:

    标签: html css material-ui


    【解决方案1】:


    不幸的是,像您那样传递 children 属性不适用于 material-ui 的 Icon 组件。它期望children 是图标字体连字的名称。

    一个可能的解决方案是根据您的要求创建一个自定义组件 - 一个 ModeCommentIconWithNumber 组件可能吗?然后它将具有预定义的样式来定位其图标和数字元素。

    以下代码将帮助您实现您想要的。你可以修改这个组件,比如接受一个icon 属性来渲染,或者接受一个定义图标颜色的color 属性。

    ...
    import { makeStyles } from "@material-ui/core/styles";
    
    const useStyles = makeStyles({
      root: {
        position: "relative",
        display: "inline-flex",
        justifyContent: "center",
        alignItems: "center"
      },
      icon: {
        fontSize: "2.5em"
      },
      count: {
        position: "absolute",
        lineHeight: 1,
        color: "#fff",
        top: "0.5em",
        fontSize: "1em"
      }
    });
    
    function ModeCommentIconWithNumber({ size = 16, count = 0 }) {
      const classes = useStyles();
    
      return (
        <div className={classes.root} style={{ fontSize: size }}>
          <ModeCommentIcon color="primary" className={classes.icon} />
          <Typography component="span" className={classes.count}>
            {count}
          </Typography>
        </div>
      );
    }
    

    【讨论】:

      【解决方案2】:

      Ciao,没有办法将文字放在图标中(就像你做的孩子一样)。您可以将Typography 放在图标之外并使用一些css。比如:

      const styles = {
        typography: {
          color: "white",
          fontSize: 13,
          position: "absolute",
          top: "1.2%",
          left: "2%"
        }
      };
      
      function TextIcon() {
        return (
          <div>
            <Typography style={styles.typography}>2</Typography>
            <ModeComment color="primary" />
          </div>
        );
      }
      

      Here 一个代码框示例。

      【讨论】:

      • 感谢您的考虑..但代码不起作用
      • @Deepakmaurya 代码正在运行。也许您不喜欢该解决方案,但它正在发挥作用。
      【解决方案3】:

      我不认为 Mui 提供这样的定制。您可以将文本与图标平行写入,并使用绝对位置将其对齐在其顶部。

      【讨论】:

        【解决方案4】:

        你可以使用材质ui的Badgelink

        <Badge 
          badgeContent={4} 
          anchorOrigin={{
            vertical: 'center',
            horizontal: 'center',
          }} 
          color="white">
           <ModeComment />
        </Badge>
        

        【讨论】:

        • 其实我想在上面写,不像徽章
        • 中心属性在anchorOrigin中没有,只有左边,右边,顶部和底部有
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-03
        • 2018-09-21
        • 1970-01-01
        • 2018-03-28
        • 2021-07-25
        • 2020-01-25
        • 2021-11-18
        相关资源
        最近更新 更多