How to import a .txt file from my source?

前端 未结 4 1110
耶瑟儿~
耶瑟儿~ 2020-12-11 14:28

I try to import a .txt file to show the text in a text box.

My code:

import React, { Component } from \'react\';
import \'./LoadMyFile.css\';
import          


        
相关标签:
4条回答
  • 2020-12-11 15:04

    You should use a json file instead:

    sample.json:

    {
      "text": "some sample text"
    }
    

    component:

    import { text } from './sample.json';
    
    console.log(text); // "some sample text"
    
    0 讨论(0)
  • 2020-12-11 15:18

    Not wanting to use fetch as it makes me have to deal with async responses. I solved my problem like this.

    1. Created a seperate .js file and assigned my text to a variable
    2. Exported the variable
    const mytext = `test
     this is multiline text.
     more text`;
    
    export default mytext ;
    
    1. In my other component, I import the file.
    import mytext from './mytextfile.js';
    
    1. I am now free to assign it to a variable or use it anywhere in my component.
     const gotTheText = mytext;
     return (<textarea defaultValue={gotTheText}></textarea>);
    
    0 讨论(0)
  • 2020-12-11 15:24

    I converted the text to base64 and then decoded it.

    const base64textfile ="Asdfsdfsf";
    export default base64textfile ;
    
    
    import { base64decode } from "nodejs-base64";
    var decodedText = base64decode(base64textfile);
    
    0 讨论(0)
  • 2020-12-11 15:27

    I've solved my problem.

      handleClick = () => {
    
        fetch('/sample.txt')
        .then((r) => r.text())
        .then(text  => {
          console.log(text);
        })  
      } 
    

    Tis link did help: Fetch local JSON file from public folder ReactJS

    0 讨论(0)
提交回复
热议问题