Material UI 如何正确对齐FormControl实现文件输入时的InputLabel标签
解决方法
你只需要主动配置InputLabel的收缩状态,同时调整原生文件输入框的外边距匹配MUI的间距规范即可,修改后的代码如下:
<FormControl fullWidth margin="dense"> <InputLabel htmlFor="my-input" shrink={true}> Photo </InputLabel> <input type="file" id="my-input" accept="image/*" style={{ marginTop: '16px' }} /> </FormControl>
改动说明
- 给
FormControl添加fullWidth、margin="dense"属性,和TextField的对应参数保持一致,保证组件宽度和紧凑间距匹配 - 给
InputLabel添加shrink={true}属性,强制标签上浮收缩,和你之前在TextField的InputLabelProps里配置的效果完全一致 - 给原生
input添加上边距,避开上浮的标签,对齐TextField的文件输入框位置;如果你的项目用MUI的sx样式方案,可以把内联style替换为sx={{ mt: 2 }},间距适配更统一 - 保留原生input的所有特性,可以直接和react-hook-form的
register绑定,能正常拿到FileList数据
内容的提问来源于stack exchange,提问作者Santhosh
相关产品推荐
相关产品推荐

