如何在反应中读取文本文件

Sal*_*ina 24 text-files readfile reactjs

截图 1 截图 2

我想从 react 项目中的文本文件中读取,但是当我尝试执行和读取时,我在控制台日志中得到了一个 HTML 示例代码。这是函数:

`onclick= () =>{
        fetch('data.txt')
            .then(function(response){
                return response.text();
            }).then(function (data) {
            console.log(data);
        })
    };`
Run Code Online (Sandbox Code Playgroud)

以及调用它的按钮:

` <button onClick={this.onclick}>click string</button>`
Run Code Online (Sandbox Code Playgroud)

小智 32

简单试试下面的代码,你就明白了

import React, { Component } from 'react';

class App extends Component {

  constructor(props) {
    super(props);
  }

  showFile = async (e) => {
    e.preventDefault()
    const reader = new FileReader()
    reader.onload = async (e) => { 
      const text = (e.target.result)
      console.log(text)
      alert(text)
    };
    reader.readAsText(e.target.files[0])
  }

  render = () => {

    return (<div>
      <input type="file" onChange={(e) => this.showFile(e)} />
    </div>
    )
  }
}

export default App;
Run Code Online (Sandbox Code Playgroud)

  • 来到这里寻找这个答案,因为从应用程序本身加载文件并不是导致我来到这里的问题。 (2认同)

KOT*_*IOS 12

尝试以下方法:

import { text } from './data.js'; // Relative path to your File

console.log(text); 
Run Code Online (Sandbox Code Playgroud)

创建一个名为 data.js 的文件并添加以下内容:

const text= "My Text goes here";

export default text;
Run Code Online (Sandbox Code Playgroud)

  • 更改“从'./data.js'导入{文本}”;到“从'./data.js'导入文本;” 让它对我有用 (3认同)

小智 12

如果你想先获得一个 .txt 文件,你必须导入它:

   import raw from '../constants/foo.txt';
Run Code Online (Sandbox Code Playgroud)

之后,您可以获取它并转换为文本:

fetch(raw)
  .then(r => r.text())
  .then(text => {
    console.log('text decoded:', text);
  });
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!这解决了我尝试加载 YAML 文件的问题。`fs` 不起作用,所以我很高兴 `fetch` 起作用了! (4认同)
  • 得到“找不到模块'../foo1/foo2.txt'或其相应的类型声明。” (3认同)