Sal*_*ina 24 text-files readfile reactjs
我想从 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)
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)
小智 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)
| 归档时间: |
|
| 查看次数: |
64808 次 |
| 最近记录: |