Jon*_*Lee 2 javascript components typescript reactjs
我正在尝试制作打字稿 + 反应文件输入组件。但是,我收到打字稿错误“对象可能为空”。我用谷歌搜索但找不到这个问题的解决方案。如何在不禁用打字稿空检查的情况下解决此问题。
我在 e.target.files[0] 上遇到错误!
这是下面的代码
import React from 'react';
export default function ImageUpload() {
const [selectedFile, setSelectedFile] = React.useState<File | string>('fileurl');
const [imagePreviewUrl, setImagePreviewUrl] = React.useState<string | undefined | ArrayBuffer | null>();
const fileChangedHandler = (e : React.ChangeEvent<HTMLInputElement>) => {
setSelectedFile(e.target.files[0]!);
const reader = new FileReader();
reader.onloadend = () => {
setImagePreviewUrl(reader.result);
};
reader.readAsDataURL(e.target.files[0]!);
};
const submit = () => {
const fd = new FormData();
fd.append('file', selectedFile);
};
let imagePreview = (<div className="previewText image-container">Please select an Image for Preview</div>);
if (imagePreviewUrl) {
imagePreview = (
<div className="image-container">
<img src={imagePreviewUrl} alt="icon" width="200" />
{' '}
</div>
);
}
return (
<div className="App">
<input type="file" name="avatar" onChange={fileChangedHandler} />
<button type="button" onClick={submit}> Upload </button>
{ imagePreview }
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
HTMLInputElement有一个内置属性filestypeof FileList | null。
Run Code Online (Sandbox Code Playgroud)files: FileList | null;
只要确保该可能性files是null。
if (!e.target.files) return;
Run Code Online (Sandbox Code Playgroud)
在函数的开头。
从代码中,我怀疑它e.target可以为空。您可以修改e.target.files[0]!为e.target!.files[0]!,这将使错误消失,因为您实际上会告诉 Typescript 编译器“它不会为空,相信我”。但相反,我建议正确处理 null 情况 - 检查 null 或未定义并执行适当的操作,具体取决于您的应用程序逻辑。
伙计们,这是处理此问题的正确方法:
e.target.files instanceof FileList
? reader.readAsDataURL(e.target.files[0]) : 'handle exception'
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。干杯!
| 归档时间: |
|
| 查看次数: |
4194 次 |
| 最近记录: |