将默认数据上载到表单



描述

我尝试了react jsonschema形式。对于我的任务,我希望使用用户可以上传的默认值,这样他就不需要再次填写整个表单。我认为最简单的方法是将一些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"));

预期行为如果我上传数据,表格应该更新并显示上传数据的内容。

实际行为我可以上传数据,表格的内容数据会发生剧烈变化。但是表单只有空字段。

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

最新更新