반응형
응답 텍스트 파일을 읽는 방법
리액트 프로젝트 내의 텍스트파일에서 읽고 싶은데 실행 및 읽기를 시도하면 콘솔로그에 HTML 샘플코드가 표시됩니다.기능은 다음과 같습니다.
`onclick= () =>{
fetch('data.txt')
.then(function(response){
return response.text();
}).then(function (data) {
console.log(data);
})
};`
그리고 그것을 부르는 버튼:
` <button onClick={this.onclick}>click string</button>`
아래 코드를 사용해 보면 알 수 있습니다.
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;
먼저 .txt 파일을 가져오려면 파일을 Import해야 합니다.
import raw from '../constants/foo.txt';
그런 다음 이를 가져와 텍스트로 변환할 수 있습니다.
fetch(raw)
.then(r => r.text())
.then(text => {
console.log('text decoded:', text);
});
다음 방법을 사용해 보십시오.
import { text } from './data.js'; // Relative path to your File
console.log(text);
data.js라는 파일을 만들고 아래 내용을 추가합니다.
const text= "My Text goes here";
export default text;
리액트는 javascript이므로 이 코드는 동작합니다.
HTML
<input type="file" id="fileInput" onchange="onLoad(event)">
Js
onLoad = function (event){
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
var content = reader.result;
//Here the content has been read successfuly
alert(content);
}
reader.readAsText(file);
}
}
데이터를 로드하고 싶은 경우 페이지 로드에서 직접 실행할 수 있습니다.
import { text } from './data.txt'; // Relative path to your File
console.log(text);
언급URL : https://stackoverflow.com/questions/55830414/how-to-read-text-file-in-react
반응형
'itsource' 카테고리의 다른 글
변경 후 각도 JS 업데이트 입력 필드 (0) | 2023.02.14 |
---|---|
ng-pattern을 사용하여 angularJs의 이메일 ID를 확인하는 방법 (0) | 2023.02.14 |
맵을 JavaScript 개체로 변환 (0) | 2023.02.14 |
Angular에서 부모 스코프 값을 ng 반복 루프에 전달합니다. (0) | 2023.02.10 |
반응 후크 - 개체 집합에서 중첩된 속성이 변경되면 useEffect를 트리거합니다. (0) | 2023.02.10 |