将默认数据上传到表单

Upload default data to a form

描述

我尝试了 react-jsonschema-form。对于我的任务,我想使用用户可以上传的默认值,这样他就不需要再次填写整个表格。我认为最简单的方法是将一些 formData 作为 json 上传,然后插入到表单中。

重现步骤

  1. 打开jsfiddle:https://jsfiddle.net/s056ceq8/33/
  2. 在相应的字段中输入名称。
  3. 提交数据。您将下载一个 hello_world.json 文件
  4. 上传 hello_world.json 文件
const Form = JSONSchemaForm.default;

const mySchema = {
  "title": "My Form",
  "description": "My Form",
  "type": "object",
  "required": [
    "name"
  ],
  "properties": {
    "name": {
      "type": "string",
      "title": "Name"
    }
  }
};

class MyForm extends React.Component {
    constructor(props) {
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.state = {
          initialData: props.initialData,
        };
    }

    onChangeUploadData  = e => {
        const fileReader = new FileReader();
        fileReader.readAsText(e.target.files[0], "UTF-8");
        fileReader.fileName = e.target.files[0].name;
        fileReader.onload = e => {
          this.setState({ initialData: e.target.result });
          console.log(this.state.initialData);
        };
    };

    handleSubmit({formData}) {
        var blob = new Blob([JSON.stringify(formData, null, 2)], { type: "application/json;charset=utf-8" });
        saveAs(blob, "hello_world.json");
        console.log(formData);
    }

    render() {
        return (
          <div>
            
            <input label="Upload File" type="file" onChange={this.onChangeUploadData}/>
          <Form schema={mySchema} onSubmit={this.handleSubmit}  formData={this.state.initialData}/>
          </div>
        )
    }
};

ReactDOM.render(<MyForm/>, 
             document.querySelector("#app"));
预期行为

如果我上传数据,表单应该更新并显示上传数据的内容。

实际行为

我可以上传数据,而 formData 的内容却发生了实际变化。但是表单只有空字段。

e.target.result 未定义。您需要将 e.target.result 替换为 JSON.parse(fileReader.result)