我使用这个反应组分将文件上传到浏览器(而不是服务器)。这个组件是react jsonschema-格式库的一部分,所以我不能更改源代码。此组件的render
方法如下所示
render() {
const { multiple, id, readonly, disabled, autofocus } = this.props;
const { filesInfo } = this.state;
return (
<div>
<p>
<input
ref={ref => (this.inputRef = ref)}
id={id}
type="file"
disabled={readonly || disabled}
onChange={this.onChange}
defaultValue=""
autoFocus={autofocus}
multiple={multiple}
/>
</p>
<FilesInfo filesInfo={filesInfo} />
</div>
);
}
该组件接受一个或多个文件作为输入,base64对它们进行编码,并将编码的文件存储在内存中。
但是,如果用户选择一个大文件(例如,5MB),则在处理过程中会出现明显的延迟。我想在这个处理开始时显示一个旋转器,并在它完成时隐藏它,但是我找不到显示/隐藏自旋器的相关事件。
如果是相关的话,我有一个到小部件的ref
,并且可以使用它通过myWidgetRef.inputRef
将一个ref
发送到<input>
字段。
发布于 2018-05-13 17:10:29
您可以将change
事件侦听器添加到输入引用中,当选择文件时将调用该事件侦听器。
仅在上传完成后才调用作为支柱传递的onChange函数。
然后使用onChange
支柱来处理处理完成。
import React from "react";
import { render } from "react-dom";
import Form from "react-jsonschema-form";
import FileWidget from "react-jsonschema-form/lib/components/widgets/FileWidget";
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = {
processing: false
};
this.inputChanged = this.inputChanged.bind(this);
}
inputChanged() {
console.log("processing");
this.setState({ processing: true });
}
componentDidMount() {
this.fileWidget.inputRef.addEventListener("change", this.inputChanged);
}
componentWillUnmount() {
this.fileWidget.inputRef.removeEventListener("change", this.inputChanged);
}
render() {
return (
<React.Fragment>
<div>Is processing: {this.state.processing + ""}</div>
<Form
schema={{
type: "object",
properties: {
file: {
type: "string",
format: "data-url"
}
}
}}
widgets={{
FileWidget: props => (
<FileWidget
{...props}
ref={ref => {
this.fileWidget = ref;
}}
onChange={() => {
console.log("processed");
this.setState({ processing: false });
}}
/>
)
}}
liveValidate
/>
</React.Fragment>
);
}
}
render(<MyForm />, document.getElementById("root"));
发布于 2018-05-09 09:09:23
onChange = () => {
this.setState({uploading: true})
//upload fetch call
fetch().then(results => {//this is dummy call
this.setState({uploading: false})
})
}
render() {
const { multiple, id, readonly, disabled, autofocus } = this.props;
const { filesInfo } = this.state;
return (
<div>
<p>
{this.state.uploading ? <div className="progress"></div> : null}
<input
ref={ref => (this.inputRef = ref)}
id={id}
type="file"
disabled={readonly || disabled}
onChange={this.onChange}
defaultValue=""
autoFocus={autofocus}
multiple={multiple}
/>
</p>
<FilesInfo filesInfo={filesInfo} />
</div>
);
}
发布于 2018-05-20 01:06:57
据我所知,您正在客户端处理这个大型文件。
因此,对于您来说,最简单的解决方案是在处理开始之前放置加载标志,在处理结束后删除它。
完成此操作后-您将遇到标记更改没有反映到DOM状态,因为呈现是延迟的。
因此,解决方案将是将代码转换为:
setLoadingFlag();
doComputing();
removeLoadingFlag();
要异步表单:
setLoadingFlag();
setTimeout(() => {
doComputing();
removeLoadingFlag();
}, 0)
这将允许对呈现加载程序作出反应。
https://stackoverflow.com/questions/50258231
复制相似问题