antd上传组件(Upload)如何设计成受控组件

https://ant-design.antgroup.com/components/upload-cn

https://github.com/ant-design/ant-design/issues/2423

useAttachment.js:

import React from 'react'
import { Button, Upload, message } from 'antd'
import { v4 as uuidv4 } from 'uuid'
import {
  imageUrlFormat,
  uploadGetTokenFromLocalStorageForH5,
} from '../../../utils/tools'
import urls from '../../../api/urls'
import { Icon } from '../../../components/light'

export default function useAttachment({
  value = '',
  type = 'add',
  fileList,
  onChange,
  accept = '*.*',
  imgUrlCnd,
  videoDir = 'ai/file',
  filePrefix = '',
  handleChangeFile,
  maxCount = 2,
  pageType,
}) {
  const imageUrl = imageUrlFormat(imgUrlCnd)

  const uploadProps = {
    name: 'file',
    action: urls.light.uploadToCDN,
    data: (file) => {
      const uid = uuidv4()
      const reslutIndex = Array.from(file.name).findLastIndex(
        (item) => item === '.'
      )
      const fileName = uid + file.name.slice(reslutIndex, file.name.length)
      return {
        key: `${videoDir}/${
          filePrefix ? filePrefix + '-' : ''
        }${Date.now()}-${fileName}`,
        fname: fileName,
        token: uploadGetTokenFromLocalStorageForH5(),
      }
    },
    headers: {},
    maxCount,
    listType: 'picture',
    defaultFileList: [],
    fileList,
    accept,
    beforeUpload(file) {
      if (fileList.length >= maxCount) {
        message.warning(`最多只能上传${maxCount}个附件`)
        return false
      }
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
        onChange(undefined)
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`)
        handleChangeFile && handleChangeFile({ info })
        if (info.file?.response.code === 200) {
          onChange(info.file.response.data.key)
        }
      } else if (info.file.status === 'uploading') {
        handleChangeFile && handleChangeFile({ info })
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`)
      } else if (info.file.status === 'removed') {
        handleChangeFile && handleChangeFile({ info })

        onChange(info.file.response.data.key)
      }
    },
  }

  const getDom = () => {
    return (
      <>
        {pageType === '7' ? (
          <span>
            {type !== 'check' ? (
              <div className="m-ai-footer-attachment-wrap">
                <Upload {...uploadProps}>
                  <Button
                    icon={
                      <Icon
                        name="attachment2"
                        className="m-ai-footer-attachment-icon"
                      ></Icon>
                    }
                  />
                </Upload>
              </div>
            ) : value ? (
              <a href={imageUrl} target="_blank" rel="noreferrer">
                {imageUrl}
              </a>
            ) : null}
          </span>
        ) : null}
      </>
    )
  }

  return {
    attactmentGetDom: getDom,
  }
}
  import useAttachment from './useAttachment'
  


  const handleOnChangeForFile = (key) => {
    // console.log(key)
  }

  const handleChangeFile = ({ info }) => {
    console.log('fileList', info.fileList)
    if (Array.isArray(info.fileList)) {
      setFileList([...info.fileList])
    }

    if (info.file?.response?.data?.key) {
      if (info.file.status === 'done') {
        Api.h5
          .fileAdd({
            name: info.file.name,
            url: info.file.response.data.key,
            info: info.file,
          })
          .then((res) => {
            if (res.code === 200) {
              //antdMessage.success('成功')
            }
          })
      }
    }
  }

  const { attactmentGetDom } = useAttachment({
    ...props,
    pageType,
    fileList,
    onChange: handleOnChangeForFile,
    handleChangeFile,
  })

人工智能学习网站

https://chat.xutongbao.top

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

徐同保

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值