我尝试导入.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文件
这在实践中效果很好:
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)
您应该改用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)
小智 5
不想使用提取,因为它使我不得不处理异步响应。我这样解决了我的问题。
const mytext = `test
this is multiline text.
more text`;
export default mytext ;
Run Code Online (Sandbox Code Playgroud)
import mytext from './mytextfile.js';
Run Code Online (Sandbox Code Playgroud)
const gotTheText = mytext;
return (<textarea defaultValue={gotTheText}></textarea>);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12043 次 |
| 最近记录: |