首页 > 解决方案 > 如何将输入目标值和 setState 值作为辅助函数的参数传递?

问题描述

我有一个看起来像这样的函数,它需要一个输入文件并将其发布到后端:

const loadFile = async ({ target }) => {
    const file = target.files[0];

    if (file) {
      const { name, size } = file;

      // TODO: CHANGE URL
      if (size > 5000000) {
        setIsUploadError('File size too big');
      } else {
        const res = await PostData(`${BACKEND_ADDRESS}/${UPLOAD_ENDPOINT}`, file, userId, isUploading, uploadError);
        if (res) {
          if (res.status === 200) {
            const resJson = await res.json();

            const newUpload = {
              id: resJson.id,
              upload: {
                id: resJson.upload_id,
                title: name,
                url: resJson.url,
              },
            };
            setIsUploadLoading(false);
          } else if (res.status === 500) {
            setIsUploadError('Error uploading');
          }
        }
      }
    }
  };
<input
  type="file"
  id="buttonUpload"
  onChange={loadFile}
/>

试图将它移动到一个辅助函数文件中,在那里添加它使用的 postData() 函数,然后导入它并调用它,如下所示:

loadFile(userId, target, setIsUploadError);

无法让它工作:

Error: target is not defined

如何从输入中获取作为参数传递的目标文件?可以像这样传递钩子 setState 值(setIsUploadError)吗?

标签: javascripthtmlreactjs

解决方案


<input
    type="file"
    id="buttonUpload"
    onChange={(e)=> loadFile(e.target)}
/>

在 onChange 函数中捕获点击事件,并将目标传递给回调函数


推荐阅读