首页 > 解决方案 > 将默认数据上传到表单

问题描述

描述

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

重现步骤

  1. 打开js小提琴: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的内容会发生变化。但表单只有空字段。

标签: reactjsreact-jsonschema-forms

解决方案


e.target.result给出未定义的。你需要替换e.target.resultJSON.parse(fileReader.result)


推荐阅读