reactjs - 将默认数据上传到表单
问题描述
描述
我尝试了 react-jsonschema-form。对于我的任务,我想使用用户可以上传的默认值,这样他就不需要再次填写整个表单。我认为最简单的方法是将一些 formData 作为 json 上传,然后将其插入表单中。
重现步骤
- 打开js小提琴:https ://jsfiddle.net/s056ceq8/33/
- 在相应字段中输入名称。
- 提交数据。您将下载一个 hello_world.json 文件
- 上传 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)
推荐阅读
- python - Tensorboard:如何查看模型摘要?
- php - 如何设置某个值但不通过它?
- algorithm - QBasic 中狐狸追逐模拟的最佳方法
- arrays - DolphinDB 数据库中的向量和数组有什么区别?
- python - using functions with variables from other python files at notebook's directory
- python - 如何检查组中的最大值并返回产品名称
- oracle - 我的问题是关于在 oracle 9i 上查询的 exportdump
- c# - 如何删除 MS LUIS 帐户并使用相同帐户重新创建
- python - Sikuli GUI 自动化 - 持续检查外部错误
- c++ - 如何在OpenGL中自动选择屏幕尺寸