React+antDesign实现上传图片功能(类组件)
import React from 'react';
import { Upload, message, Button } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
class ImageUpload extends React.Component {
constructor(props) {
super(props);
this.state = {
imageUrl: '',
};
}
handleChange = info => {
if (info.file.status === 'uploading') {
return;
}
if (info.file.status === 'done') {
// 获取上传成功后的图片链接
this.setState({ imageUrl: info.file.response.url });
message.success(`图片上传成功`);
if (this.props.onChange) {
this.props.onChange(info.file.response.url);
}
}
}
render() {
const { imageUrl } = this.state;
const uploadButton = (
<Button icon={<UploadOutlined />} href="#">
上传图片
</Button>
);
return (
<Upload
name="avatar"
listType="picture-card"
className="image-upload"
showUploadList={false}
action="https://www.mocky.io/v2/5cc8019d300000980a055e76" // 替换为你的图片上传API
onChange={this.handleChange}
>
{imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
</Upload>
);
}
}
export default ImageUpload;
这段代码实现了一个简单的图片上传功能,用户可以点击上传按钮选择图片,图片会被上传到指定的API,并在上传成功后展示图片。此外,它还包含了错误处理和状态管理,以确保用户界面能够正确反映当前的状态。
评论已关闭