首页 > 解决方案 > 文件上传开始/完成时显示/隐藏微调器

问题描述

我正在使用这个 React 组件将文件上传到浏览器(而不是服务器)。该组件是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.

标签: javascriptreactjs

解决方案


You can add the changeevent listener to the input ref, which will be called when a file is selected.

仅在上传完成时调用作为 prop 传递的 onChange 函数

然后使用onChange道具来处理处理完成。

编辑 n5vk9z426p

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"));

推荐阅读