Nor*_*ldt 4 html ecmascript-6 reactjs
我似乎无法弄清楚如何加载本地 .json 文件并读取内容 - 所以我可以将它转储到某个“状态”中。
到目前为止,代码看起来像这样:
import React, { Component } from 'react'
import Files from 'react-files'
class LoadFile extends Component {
render() {
return (
<div className="files">
<Files
className="files-dropzone"
onChange={file => {
console.log(file)
}}
onError={err => console.log(err)}
accepts={['.json']}
multiple
maxFiles={3}
maxFileSize={10000000}
minFileSize={0}
clickable
>
Drop files here or click to upload
</Files>
</div>
)
}
}
export default LoadFile
Run Code Online (Sandbox Code Playgroud)
记录的对象没有任何隐藏在其中的数据。
[Object]
0: Object
id: "files-1"
extension: "json"
sizeReadable: "288B"
preview: Object
type: "file"
Run Code Online (Sandbox Code Playgroud)
就像@dkniffin 说的,后面react-files是DataTransfer。
您可以使用FileReader API 来获取文件内容并以 JSON 格式解析它,您可以在下面的 CodeSandbox 的控制台部分看到结果:
constructor() {
super();
this.state = {
jsonFile: {}
};
this.fileReader = new FileReader();
this.fileReader.onload = (event) => {
// or do whatever manipulation you want on JSON.parse(event.target.result) here.
this.setState({ jsonFile: JSON.parse(event.target.result) }, () => {
console.log(this.state.jsonFile);
});
};
}
...
render() {
return (
<div className="files">
<Files
...
onChange={file => {
// we choose readAsText() to load our file, and onload
// event we rigister in this.fileReader would be triggered.
this.fileReader.readAsText(file[0]);
}}
>
Drop files here or click to upload
</Files>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)