使用label的htmlFor属性修改样式
jsx部分:
const [preImg, setPreImg] = useState<string>()
const [uploading, setUploading] = useState(false)
const choseImg = async (e: any) => {
try {
const {formData, base64}: {formData: any; base64: string} = await lrz(e.target.files[0], {
width: 750,
fieldName: 'imageAML',
})
uploadImage(formData, base64)
} catch (e) {
console.log(e)
}
}
const uploadImage = (formData: any, base64: string) => {
// 调用接口 上传文件 上传成功 setPreImg(base64)
setPreImg(base64)
}
return (
<div className='photo_upload'>
<div className='card'>
<label htmlFor='upload'>
{preImg ? (
<img className='photo' alt='证件照' src={preImg} />
) : (
<div className='portrait'>
{uploading && (
<div className='loading_div'>
<Loading color='white' />
<span>上传中...</span>
</div>
)}
</div>
)}
</label>
</div>
<input
type='file'
accept='image/*'
id='upload'
onChange={(e: any) => choseImg(e)}
/>
</div>
)
样式部分:
.photo_upload .card{
display: flex;
justify-content: center;
align-items: center;
position: relative;
margin-bottom: 60px;
}
.photo_upload .card .photo{
width: 305px;
height: 165px;
object-fit: contain;
border-radius: 10px;
}
.photo_upload .portrait{
background-color: skyblue;
height: 200px;
width: 200px;
}
.photo_upload input{
display: none;
}
.photo_upload .loading_div{
display: flex;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.2);
border: none;
border-radius: 10px;
font-size: 12px;
color: #fff;
flex-direction: column;
justify-content: center;
align-items: center;
}
本文介绍了如何在React Hooks应用中,利用input标签结合CSS自定义样式来实现图片上传和预览功能。通过label的htmlFor属性改变样式,提升用户体验。

被折叠的 条评论
为什么被折叠?



