将Upload组件放入src/components下成为全局组件
调用时通过子组件向父组件传值实现的,这里的子组件为全局组件下的Upload上传组件,父组件指的是调用时的路由组件。
上传图片一般为是为了得到上传到服务器后的图片路径。
具体配置如下:
在Upload组件中接受父组件传递过来的函数,在onChange事件的上传成功时调用此函数,为此函数传递为上传到服务器后的图片路径为实参,这时父组件内的函数代码块会被执行,形参也就是子组件传过来的图片路径了,这时使用一个状态set为此值就能够完成表单的收集了。
拿头像上传为示例:
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { Upload } from 'antd';
import React, { useState } from 'react';
const App = ({ pic }) => {
const [loading, setLoading] = useState(false);
const [imageUrl, setImageUrl] = useState();
const getBase64 = (img, callback) => {
const reader = new FileReader();
reader.addEventListener('load', () => callback(reader.result));
reader.readAsDataURL(img);
};
return (
<>
<Upload
name="image"
listType="picture-card"
className="avatar-uploader"
showUploadList={false}
action="上传接口url"
onChange={(info) => {
if (info.file.status === 'uploading') {
setLoading(true);
return;
}
if (info.file.status === 'done') {
getBase64(info.file.originFileObj, (url) => {
console.log(info.file);
setLoading(false);
setImageUrl(url);
pic(info.file.response.url); //调用父组件传递过来的函数,并传递实参为上传成功的图片路径
});
}
}}
>
{imageUrl ? (
<img
src={imageUrl}
alt="avatar"
style={{
width: '100%',
}}
/>
) : (
<div>{loading ? <LoadingOutlined /> : <PlusOutlined />}</div>
)}
</Upload>
</>
);
};
export default App;