将FileReader与React和Typescript一起使用
我想使用输入使用类型文件上传JSON文件。当我在Fileerer thexcript上使用Onload方法时,请显示我错误 - 无法调用可能是“ 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>
)
}
I want to upload json file using input with type file. When I use onload method on fileReder Typescript shows me error - Cannot invoke an object which is possibly 'null'.
Thank you.
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>
)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这应该有效:
This should work:
分配它来定义事件侦听器:
Assign it to define the event listener: