reactjs 将FileReader与React和Typescript配合使用

dphi5xsq  于 2023-03-08  发布在  React
关注(0)|答案(1)|浏览(149)

我想使用类型为file的输入上传json文件。当我在fileReder上使用onload方法时,Typescript显示错误-无法调用可能为'null'的对象。谢谢。

const UploadCharacter = () => {
    const [data, setData] = useState<any>();

    const handleUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files) {
            const fileReader = new FileReader(); 
            fileReader.readAsText(e.target.files[0], 'UTF-8')
            fileReader.onload((e) => {  <-- Error: Cannot invoke an object which is possibly 'null'.
                console.log(e.target.result)
            })
        }

    }
    return (
        <div className={s.upload}>
            <input
                className={s.uploadInput}
                type="file"
                onChange={handleUpload}
            />
        </div>
    )
}
v8wbuo2f

v8wbuo2f1#

这应该行得通:

const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      const reader = new FileReader();
      reader.readAsText(e.target.files[0], 'UTF-8');
      reader.onloadend = (readerEvent: ProgressEvent<FileReader>) => {
        if (readerEvent?.target?.result) {
          setPolicy(readerEvent.target.result.toString());
          updatePolicy(readerEvent.target.result.toString());
        }
      };
    }
  };

相关问题