javascript - 如何将输入目标值和 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)吗?
解决方案
<input
type="file"
id="buttonUpload"
onChange={(e)=> loadFile(e.target)}
/>
在 onChange 函数中捕获点击事件,并将目标传递给回调函数
推荐阅读
- video - 播放器如何解析 MP4 文件并播放其中的曲目?
- java - 简单的 HTML 登录表单
- aws-lambda - 为什么我们已经拥有 Azure 函数、AWS Lambda、谷歌云函数时还需要 Spotinst 函数
- c# - 修改列表中的最后一项
- javascript - “发送”未定义?| 不和谐.js
- python - 预期 conv2d_1_input 有 4 个维度,但得到了形状为 (15936, 64) 的数组
- android - Android 如何将 setOnEditorActionListener 添加到 EditTexts 列表
- html - 不能在同一行设置 div
- ansible - 将 bash 转换为 ansible - 替换包含单词的行
- server - jmeter如何开始向服务器发送请求