我正在尝试制作打字稿 + 反应文件输入组件。但是,我收到打字稿错误“对象可能为空”。我用谷歌搜索但找不到这个问题的解决方案。如何在不禁用打字稿空检查的情况下解决此问题。
我在 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 …Run Code Online (Sandbox Code Playgroud)