Reactでファイルの内容を読み込む方法
Reactでは、fetch()関数、あるいはaxiosライブラリを使用することでファイル内容の読み取りが可能です。
fetch() 関数を使用します
fetch('path/to/file.txt')
.then(response => response.text())
.then(data => {
// 处理文件内容
console.log(data);
})
.catch(error => {
// 处理错误
console.log(error);
});
axiosライブラリを使用する:
axios.get('path/to/file.txt')
.then(response => {
// 处理文件内容
console.log(response.data);
})
.catch(error => {
// 处理错误
console.log(error);
});
Reactコンポーネントで利用する場合は、fetch()関数でもaxiosライブラリでもインポートが必要です。