实现的功能如图:
上代码:
Upload_cir.js
import React, { useRef, useState } from 'react';
import "./App.css"
const Upload_cir = () => {
const [selectedFile, setSelectedFile] = useState(null);
const [previewUrl, setPreviewUrl] = useState('');
const fileInputRef = useRef(null);
const handleFileChange = (event) => {
const file = event.target.files[0];
if (file) {
setSelectedFile(file);
const reader = new FileReader();
reader.onloadend = () => {
setPreviewUrl(reader.result);
};
reader.readAsDataURL(file);
}
};
const handleImageClick = () => {
fileInputRef.current.click();
};
return (
<div>
<h2>请选择图片进行上传</h2>
<input
type="file"
style={{ display: 'none' }}
ref={fileInputRef}
onChange={handleFileChange}
accept="image/*"
/>
{/* 展示框容器 */}
<div className="image-container" onClick={handleImageClick}>
{/* 根据是否选择了图片来显示不同的内容 */}
{previewUrl ? (
<img
src={previewUrl}
alt="Uploaded Image"
className="preview-image"
/>
) : (
<img
src="upload.jpg" // 上传按钮图片资源
alt="Upload Image"
style={{ cursor: 'pointer', width: '1000px', height: '1000px' }}
className="upload-button"
/>
)}
</div>
</div>
);
};
export default Upload_cir;
App.css:
.image-container {
position: relative; /* 使子元素可以相对于这个容器进行定位 */
width: 320px; /* 稍大于图片的宽度 */
height: 320px; /* 稍大于图片的高度 */
border: 2px dashed #ccc; /* 可选的边框样式,表示点击区域 */
display: flex; /* 使用Flexbox布局来居中图片 */
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
cursor: pointer; /* 鼠标悬停时显示点击效果 */
text-align: center;
}
.preview-image,
.upload-button {
max-width: 300px; /* 图片最大宽度 */
max-height: 300px; /* 图片最大高度 */
object-fit: contain; /* 保持图片宽高比,同时适应容器大小 */
opacity: 0.8; /* 可选的透明度,以区分上传按钮和预览图片 */
transition: opacity 0.3s ease; /* 平滑的透明度过渡效果 */
}
App.js
import React from 'react';
import Upload_cir from "./Upload_cir.js";
function App() {
return (
<Upload_cir/>
);
}
export default App;