You need to enable JavaScript to run this app. 如何清空React Dropzone文件输入及成功图标,恢复初始拖拽状态
优惠活动
大模型
产品
解决方案
定价
更多

如何清空React Dropzone文件输入及成功图标,恢复初始拖拽状态

实现文件上传后重置组件的方案

实现步骤

  • 新增handleClear重置函数,调用现有状态更新方法清空文件列表、重置错误状态
  • 在文件已上传的渲染分支中添加清除按钮,绑定点击事件触发handleClear
  • 修正原有代码的语法、变量名拼写错误,保证组件可正常运行

完整修正后代码

export interface MyDropZone extends DropzoneProps {
  onChange?: (acceptedFiles: File[]) => void;
}

const MyDropzone: FC<MyDropZone> = (props: MyDropZone) => {
  const [file, setFile] = React.useState<null | File[]>(null);
  const [errorStatus, setErrorStatus] = React.useState(false);

  // 重置组件状态的处理函数
  const handleClear = () => {
    setFile(null);
    setErrorStatus(false);
  };

  const onDropAccepted = useCallback(async (acceptedFiles) => {
    // 此处保留你原有的上传逻辑
    const response = await 你的实际上传接口(acceptedFiles);
    setFile(acceptedFiles);
    if (!response.ok) {
      setErrorStatus(true);
    }
  }, []);
  
  return (
    <Box>
      {!!file ? (
        <p>
          {errorStatus ? (
            <Icon icon={'Close'} color="danger"/>
          ) : (
            <Icon icon={'Checkmark'} color="success"/>
          )}
          {file.map((item: File) => item.name).join(",")}
          {/* 清除按钮,可根据你使用的UI库替换为对应按钮组件 */}
          <Icon 
            icon={'Close'} 
            onClick={handleClear} 
            style={{ marginLeft: '8px', cursor: 'pointer' }} 
            aria-label="清除上传文件"
          />
        </p>
      ) : (
        <p>Drag and drop</p>
      )}
    </Box>
  );
};

内容的提问来源于stack exchange,提问作者Srishti Roy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 02:18:03