首页 > 解决方案 > 如何动态改变 UI Chip 的大小

问题描述

在下面的示例中,我尝试动态更改 UI 芯片的大小,以便使用该em css单位响应其父级的字体大小。

我的目标:我想做这样的事情

style={{size:'1em'}}

我的问题:material-ui 中的芯片元素不像大多数 material-UI 组件那样可调整大小。

我试过:

  1. style={{transform:'scale(1em)'}}但它根本不起作用。我不知道如何改变变换的锚点。
  2. 我也尝试创建自己的芯片,<img style={{float: 'left', width: '1em', borderRadius: '50%',}}/>但它看起来不像材料 UI 芯片那样原始。
import Avatar from '@material-ui/core/Avatar'
import Chip from '@material-ui/core/Chip'

function Chips() {
  const classes = useStyles()

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

  const handleClick = () => {
    console.info('You clicked the Chip.')
  }

  return (
    <div className={classes.root}>
      <h1>
        <Chip
          //style={{size:'1em'}}
          avatar={<Avatar alt="Natacha" src="/static/images/avatar/1.jpg" />}
          label="Deletable"
          onDelete={handleDelete}
        />
      </h1>

      <h4>
        <Chip
          //style={{size:'1em'}}
          avatar={<Avatar alt="Natacha" src="/static/images/avatar/1.jpg" />}
          label="Deletable"
          onDelete={handleDelete}
        />
      </h4>
    </div>
  )
}

标签: htmlcssreactjsmaterial-ui

解决方案


目前,Chip不支持尺寸道具(希望他们将来支持它)。
为此,您必须制作自己的自定义组件。我创建了一个名字CustomChip

在此,传递一个名为 的道具size,芯片的其余大小会相应地缩放。

CustomChip.js

function CustomChip(props) {
  const { size = 1, ...restProps } = props;
  const classes = useStyles({ size });

  return (
    <Chip
      className={classes.root}
      classes={{ avatar: classes.avatar, deleteIcon: classes.deleteIcon }}
      {...restProps}
    />
  );
}

const useStyles = makeStyles((theme) => ({
  root: {
    fontSize: (props) => `${props.size * 0.8125}rem`,
    height: (props) => `${props.size * 32}px`,
    borderRadius: "9999px"
  },
  avatar: {
    "&&": {
      height: (props) => `${props.size * 24}px`,
      width: (props) => `${props.size * 24}px`,
      fontSize: (props) => `${props.size * 0.75}rem`
    }
  },
  deleteIcon: {
    height: (props) => `${props.size * 22}px`,
    width: (props) => `${props.size * 22}px`,
    color: "green"
  }
}));

这里提供的尺寸乘以零件的默认尺寸。

采用:-

<CustomChip
    size={2}
    avatar={<Avatar alt="Natacha" src="/static/images/avatar/1.jpg" />}
    label="Deletable"
    onDelete={handleDelete}
/>

工作沙箱链接:-

编辑 crazy-blackwell-987it


推荐阅读