如何在 React 中使用 FileReader? [英] How to use FileReader in React?

查看:100
本文介绍了如何在 React 中使用 FileReader?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让用户选择文本文件"并将其显示在那里.稍后,我将使用txt文件中的数据进行绘图.但是,我无法显示txt文件的内容.

I am trying to let user to "choose text file" and display it there. Later, I'll use the data in txt file to plot. However, I couldn't display the content of txt file.

有几个模块可用,但我不知道如何让它在 React 中工作.

There are several modules available but I don't know how to make it work in React.

有人知道吗?

以下是我找到的示例:

https://stackoverflow.com/a/40146883/10056318

 jsfiddle.net/0GiS0/nDVYd/

谢谢

推荐答案

我在 MDN 文档中找到了那个代码片段,它解决了我的问题,我希望这可以帮助其他人:

I found that code snippet on MDN Documentation, and that solved my problem i am hopping that this could help someone else:

// Callback from a <input type="file" onchange="onChange(event)">
function onChange(event) {
  var file = event.target.files[0];
  var reader = new FileReader();
  reader.onload = function(event) {
    // The file's text will be printed here
    console.log(event.target.result)
  };

  reader.readAsText(file);
}

更多信息请访问 https://developer.mozilla.org/pt-BR/docs/Web/API/FileReader/onload

这篇关于如何在 React 中使用 FileReader?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆