如何在React js中使用Hooks实现图片上传/浏览及网页端展示
React Hooks实现本地图片选择预览
实现逻辑
- 用
useStateHook分别存储选中的图片文件对象、图片预览的Base64地址 - 用原生
FileReaderAPI读取用户选中的图片文件,生成可直接用于img标签展示的Data URL - 通过隐藏原生file类型input、用label触发选择的方式,自定义选择按钮样式,符合通用交互逻辑
完整代码实现
import { useState } from 'react'; function ImagePreviewer() { // 存储选中的文件对象 const [selectedFile, setSelectedFile] = useState(null); // 存储图片预览地址 const [previewUrl, setPreviewUrl] = useState(''); const handleFileChange = (e) => { const file = e.target.files[0]; if (!file) return; // 校验是否为图片类型 if (!file.type.startsWith('image/')) { alert('请选择图片类型文件'); return; } setSelectedFile(file); // 读取文件生成预览地址 const reader = new FileReader(); reader.onload = () => { setPreviewUrl(reader.result); }; reader.readAsDataURL(file); }; return ( <div style={{ maxWidth: '500px', margin: '20px auto' }}> {/* 隐藏原生input,用label触发选择 */} <label htmlFor="image-upload" style={{ display: 'inline-block', padding: '8px 16px', background: '#165DFF', color: '#fff', borderRadius: '4px', cursor: 'pointer', marginBottom: '20px' }} > 选择图片 </label> <input id="image-upload" type="file" accept="image/*" onChange={handleFileChange} style={{ display: 'none' }} /> {/* 预览区域 */} <div style={{ width: '100%', minHeight: '300px', border: '2px dashed #eee', borderRadius: '8px', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden' }} > {previewUrl ? ( <img src={previewUrl} alt="预览图" style={{ width: '100%', height: 'auto', objectFit: 'contain' }} /> ) : ( <span style={{ color: '#999' }}>请选择图片进行预览</span> )} </div> </div> ); } export default ImagePreviewer;
可扩展优化点
- 如果需要限制图片大小,可在
handleFileChange方法中添加file.size的校验逻辑 - 如果需要多图预览,可将state改为数组类型,循环读取多个文件生成预览地址
- 可添加上传进度、删除选中图片等扩展功能
内容的提问来源于stack exchange,提问作者Ganesh
相关产品推荐
相关产品推荐

