next.js 如果URL为空,则不在antd-Upload中显示文件列表

92vpleto  于 2022-11-23  发布在  其他
关注(0)|答案(3)|浏览(184)

在这里,我传递URL作为一个道具,以显示上传的文件在编辑模态。所有我想要的是,不显示任何附件,如果URL是空的。我可以看到空的附件,如图所示:

export const FileUploader = ({ label, Url, setUrl, editMode }) => {
  console.log("Url", Url);
  const props = {
    maxCount: 1,
    onChange(info) {
      if (info.file.status !== "uploading") {
        console.log(info.file, info.fileList);
      }
    },
    fileList: [
      Url ? {
        uid: "1",
        name: label + ".png",
        status: "done",
        response: '{"status": "success"}',
        url: Url,
      } : "",
    ],
  };
wydwbb8l

wydwbb8l1#

对于收音机:

<Radio value={"True"} checked={hasOutdoorSpace}>True</Radio>
<Radio value={"False"} checked={!hasOutdoorSpace}>False</Radio>

对于Upload,您需要使用defaultFileListfileList属性。

3ks5zfa0

3ks5zfa02#

您的条件是错误的,因为没有Url时,条件的结果是fileList = [""],但您需要有fileList = [],因此您需要将条件重新定位到数组之外,如下所示:

export const FileUploader = ({ label, Url, setUrl, editMode }) => {
  const props = {
    maxCount: 1,
    onChange(info) {
      if (info.file.status !== "uploading") {
        console.log(info.file, info.fileList);
      }
    },
    fileList:Url ? [
       {
        uid: "1",
        name: label + ".png",
        status: "done",
        response: '{"status": "success"}',
        url: Url,
      } 
    ] : [],
  };
a0x5cqrl

a0x5cqrl3#

我找到了解决此问题的变通方法。
props中的fileList属性将生成一个列表(甚至是空的),因此我在Upload中使用了showUploadList属性,如果发现fileList的长度为零,则将其设置为false。
下面是代码:

import { Button, Upload } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import { useState } from "react";

export const FileUploader = ({ label, Url, setUrl, editMode }) => {
  console.log("Url", Url);
  const fileList = [
    Url
      ? {
          uid: "1",
          name: label + ".png",
          status: "done",
          response: '{"status": "success"}',
          url: Url,
        }
      : {},
  ];
  const fileExists = Object.keys(fileList[0]).length;
  const props = {
    maxCount: 1,
    onChange(info) {
      if (info.file.status !== "uploading") {
        console.log(info.file, info.fileList);
      }
    },
    fileList: fileList,
  };

  const showUploadList = editMode ? true : false;
  if(showUploadList){
    showUploadList = fileExists > 0 ? true : false;
  } 

  return (
    <Upload {...props} customRequest={addFile} showUploadList={showUploadList}>
      <Button icon={<UploadOutlined />}>Click to Upload (Max: 1) </Button>
    </Upload>
  );
};

相关问题