React Material UI 上传按钮额外显示原生文件输入框样式问题
问题原因
属于代码写法错误,不是MUI 5.8.4版本的共性问题。
MUI基础Input组件渲染type="file"类型时,默认不会自动隐藏原生文件选择控件,官方上传按钮示例本身就要求给文件类型Input添加display: none样式,你的代码漏了这部分配置。另外第二个Input标签上的sx=/是无效语法,本身不会产生任何样式效果。
修复方法
给所有绑定文件选择功能的Input组件添加sx={{ display: 'none' }}属性即可,和你之前验证的可行方案完全一致。
修复后的完整代码:
import React from 'react' import { Button, Box, Stack, Input, Typography, IconButton } from '@mui/material' import { PhotoCamera } from '@mui/icons-material' function PlainButton() { return ( <Stack spacing={3}> <Box> <Typography sx={{marginTop:1, marginLeft:1}}>Upload Button</Typography> <label htmlFor="contained-button-file"> <Input accept="image/*" id="contained-button-file" multiple type="file" sx={{ display: 'none' }} /> <Button variant="contained" component="span"> Upload </Button> </label> <label htmlFor="icon-button-file"> <Input accept="image/*" id="icon-button-file" type="file" sx={{ display: 'none' }} /> <IconButton color="primary" aria-label="upload picture" component="span"> <PhotoCamera /> </IconButton> </label> </Box> </Stack> ) } export default PlainButton
原理说明:外层
<label>通过htmlFor属性和Input的id绑定后,点击label内的任意元素都会自动触发关联Input的默认行为,因此隐藏原生Input控件完全不影响文件选择功能。
异常效果

项目环境
- React版本:18.2.0
- @emotion/react:11.9.3
- @emotion/styled:11.9.3
- @mui/icons-material:5.8.4
- @mui/material:5.8.4
- 测试浏览器:Chrome
内容的提问来源于stack exchange,提问作者timothy jeong
相关产品推荐
相关产品推荐

