html - 如何动态改变 UI Chip 的大小
问题描述
在下面的示例中,我尝试动态更改 UI 芯片的大小,以便使用该em
css
单位响应其父级的字体大小。
我的目标:我想做这样的事情
style={{size:'1em'}}
我的问题:material-ui 中的芯片元素不像大多数 material-UI 组件那样可调整大小。
我试过:
style={{transform:'scale(1em)'}}
但它根本不起作用。我不知道如何改变变换的锚点。- 我也尝试创建自己的芯片,
<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>
)
}
解决方案
目前,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}
/>
工作沙箱链接:-
推荐阅读
- ios - 反应原生 forceRTL false 在 iOS 上不起作用
- nestjs - 使用 NVM 设置 NestJS 项目时出现 EBADENGINE 警告
- mysql - SQL计算具有行值的不同列
- flutter - 错误:不能将“String”类型的值分配给“int”类型的变量
- perl - 停止使用 DB::DB 创建的探查器以再次显示未真正调用的调用
- android - Android Compose MVVM 多网络调用
- json - 如何在列表中显示列的所有文本?
- arrays - 我在 malloc 哪里做错了?
- git - 相当于 p4 sync -n 的 git 命令
- c# - 如何使用 Graph Api 替换 Onedrive 中的文件?