如何从我的源中导入.txt文件?

Ede*_*fix 14 reactjs

我尝试导入.txt文件以在文本框中显示文本.

我的代码:

import React, { Component } from 'react';
import './LoadMyFile.css';
import myText from './sample.txt';

export default class LoadMyFile extends Component {  
  render() {
    return (
      <div>      
        <button onClick={this.handleClick} className="LoadMyFile" name="button" variant="flat">test string</button>
      </div>
    )
  }  
  handleClick = () => {
    console.log(myText);
  }   
}
Run Code Online (Sandbox Code Playgroud)

但我在控制台中看到:/static/media/sample.f2e86101.txt

这里出了什么问题?

Ede*_*fix 12

我已经解决了我的问题.

  handleClick = () => {

    fetch('/sample.txt')
    .then((r) => r.text())
    .then(text  => {
      console.log(text);
    })  
  } 
Run Code Online (Sandbox Code Playgroud)

Tis链接确实有帮助: 从公用文件夹ReactJS获取本地JSON文件


Sim*_* B. 8

这在实践中效果很好:

import React from 'react';
import textfile from "../assets/NOTES.txt";

function Notes() {
  const [text, setText] = React.useState();
  fetch(textfile)
    .then((response) => response.text())
    .then((textContent) => {
      setText(textContent);
    });
  return text || "Loading...";
}
Run Code Online (Sandbox Code Playgroud)


riw*_*iwu 6

您应该改用json文件:

sample.json:

{
  "text": "some sample text"
}
Run Code Online (Sandbox Code Playgroud)

成分:

import { text } from './sample.json';

console.log(text); // "some sample text"
Run Code Online (Sandbox Code Playgroud)

  • 谢谢您的回答,但它是一个 .txt 文件。我没有选择。有没有办法将文本文件转换为 json 文件,或者没有其他方法作为 json 格式? (4认同)

小智 5

不想使用提取,因为它使我不得不处理异步响应。我这样解决了我的问题。

  1. 创建一个单独的.js文件并将我的文本分配给一个变量
  2. 导出变量
const mytext = `test
 this is multiline text.
 more text`;

export default mytext ;
Run Code Online (Sandbox Code Playgroud)
  1. 在其他组件中,我导入文件。
import mytext from './mytextfile.js';
Run Code Online (Sandbox Code Playgroud)
  1. 现在,我可以随意将其分配给变量或在组件中的任何位置使用它。
 const gotTheText = mytext;
 return (<textarea defaultValue={gotTheText}></textarea>);
Run Code Online (Sandbox Code Playgroud)

  • 投了反对票。无法解决导入“.txt”文件的问题。 (4认同)