我只想只允许上传一张图像,所以如果用户再次单击上传,则只能预览一张图像 ...而不是2。
我已经知道如何仅上传1张图片,但是无法弄清楚如何使用Ant Upload的图片预览来仅预览一张图片。
代码示例:
import { Upload, Button } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
const fileList = [
{
uid: '-1',
name: 'xxx.png',
status: 'done',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
}
];
ReactDOM.render(
<>
<Upload
action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
listType="picture"
defaultFileList={[...fileList]}
>
<Button icon={<UploadOutlined />}>Upload</Button>
</Upload>
<br />
<br />
<Upload
listType="picture"
defaultFileList={[...fileList]}
>
<Button icon={<UploadOutlined />}>Upload</Button>
</Upload>
</>,
mountNode,
);
答案 0 :(得分:0)
您需要通过指定Upload
属性使fileList
组件成为受控制的组件。
const [fileList, setFileList] = useState([...])
<Upload fileList={fileList}>
<Button icon={<UploadOutlined />}>Upload</Button>
</Upload>
如果您尝试上面的代码,您将注意到在上传内容时没有任何反应。要更改它,您需要修改Upload onChange
回调上的状态。有关上传onChange
道具的更多信息,请参见此link。要仅预览一张图片,只需将状态设置为仅上一次上传。
const [fileList, setFileList] = useState([...])
const handleChange = (info) => {
let fileList = [...info.fileList];
// 1. Limit the number of uploaded files
// Only to show the last recent uploaded files, and old ones will be replaced by the new
fileList = fileList.slice(-1);
setFileList(fileList);
};
<Upload fileList={fileList} onChange={handleChange}>
<Button icon={<UploadOutlined />}>Upload</Button>
</Upload>
在此处查看完整的代码: