【问题标题】:How change the size of UI Chip dynamically如何动态改变 UI Chip 的大小
【发布时间】:2021-04-03 08:56:30
【问题描述】:

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

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

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

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

我试过了:

  1. style={{transform:'scale(1em)'}} 但它根本不起作用。不知道怎么改变transform的锚点。
  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>
  )
}

【问题讨论】:

标签: html css reactjs material-ui


【解决方案1】:

目前,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}
/>

工作沙盒链接:-

【讨论】:

  • 哦,非常感谢,这真的很棒。 You may list this 这是一个 github 存储库,我正在尝试克隆概念,我正在寻找类似的贡献者
  • 我正在尝试使用 em 而不是 rem。另外,我不想添加大小值,但我需要它来动态响应其父母的字体大小,所以我制作了this,但我遇到了对齐问题!alignment
  • 我会尝试解决这个问题。
猜你喜欢
  • 1970-01-01
  • 2018-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-15
  • 1970-01-01
  • 2011-01-25
相关资源
最近更新 更多