[英]How can I import text file on React?
我的代碼在同一目錄中有以下文本文件:
Text1.txt
:
This is text1
Text2.txt
This is text2
我想制作一個頁面,當用戶單擊一個列表時,每個列表都與一個文本文件連接,文本文件的內容將顯示在控制台中。 我該怎么做?
App.js
import React, { Component } from 'react';
import './Text1.txt';
import './Text2.txt';
class App extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h1>Text Lists</h1>
<div>
<h2 onClick={this.showTitle}><li>Click this to show text1</li></h2>
<h2 onClick={this.showTitle}><li>Click this to show text2</li></h2>
</div>
</div>
);
}
}
export default App;
假設您在實現中使用 webpack,您將需要使用file-loader
來執行此操作。 你可以在這里閱讀如何。 如果您對css
或任何其他樣式加載器執行過相同操作,這將非常簡單。
module.exports = {
module: {
rules: [
{
test: /\.(txt)$/i,
loader: 'file-loader',
options: {
publicPath: 'assets',
},
},
],
},
};
加載程序設置好后,您應該能夠像導入模塊一樣導入它
import textfile from './Text1.txt';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.