我正在使用this React component将文件上传到浏览器(而不是服务器)。该组件是react-jsonschema-form库的一部分,因此我无法更改源代码。该组件的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
,可以使用它通过ref
将<input>
获取到myWidgetRef.inputRef
字段。 最佳答案
您可以将 change
事件监听器添加到输入REF,当选择一个文件,该文件会被调用。
然后使用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"));