【问题标题】:How to delete a file in antd Upload component如何在antd Upload组件中删除文件
【发布时间】:2022-01-23 00:54:49
【问题描述】:

我有这个从 antd 获得的 Upload 组件:react ant design documentation

<Upload
  beforeUpload={()=> {
    return false; }}
  onChange={e => onChangeFile(e, index)}
  onRemove={e => onRemoveFile(e, index)}
>
  <Button
    icon={<UploadOutlined />}
  >
    Upload a file
  </Button>
</Upload>

上传文件后,会出现一个删除图标。当我单击删除按钮时,文件不会从状态中删除。

这里是 onChange 函数:

const onChangeFile = (info, index) => {
    console.log("onChange info = " + info);
    const newForm = form;
    newForm.inputs[index].value = info.file;
    setForm({
      ...form,
      from: newForm
    });
    console.log("onChange form = " + form);
};

我尝试使用这样的 onRemove 函数删除它:

const onRemoveFile = (info, index) => {
   console.log("onRemove info = " + info);
   const newForm = form;
   newForm.inputs[index].value = null;
   setForm({
     ...form,
     from: newForm
   });
   console.log("onRemove form = " + form);
};

控制台日志的输出:

用户界面截图:

在 antd 提供的这个代码示例中随意尝试一些东西:

https://codesandbox.io/s/qj6n3?file=/index.js

【问题讨论】:

  • 配合antd使用&lt;Form&gt;,会自动处理很多场景
  • 我在
    中使用它,然后在
    中使用它。但我不知道如何删除上传的文件。
  • 在提交表单时,antd 表单总是返回更新后的值
  • 不要为其创建状态,在提交表单时获取文件列表值
  • 发布了答案,希望对您有所帮助,谢谢

标签: javascript reactjs antd


【解决方案1】:

您可以通过以下示例来实现:

const normFile = (e) => {
    if (Array.isArray(e)) {
        return e;
    }
    return e && e.fileList;
};

<Form onFinish={() => {}}>
    <Form.Item
        name="tagList"
        label="Upload"
        valuePropName="list"
        getValueFromEvent={normFile}
        rules={[
            {
                required: true,
                message: 'Tag list is required',
            },
        ]}
    >
        <Upload
            beforeUpload={() => false}
            listType="picture-card"
        >
            <UploadOutlined style={{ marginRight: 5 }} />
            Upload
        </Upload>
    </Form.Item>
</Form>

【讨论】:

    猜你喜欢
    • 2012-10-19
    • 2020-02-13
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多