我有一个 React 组件,它有一个获取用户输入的表单。我希望能够将此数据写入文件,而不是发送表单数据的常规提交按钮,以便以后使用.
这可以使用 vanilla JS 完成吗,或者是否有一个可能更有帮助的库?
我的句柄提交方法如下所示:
handleSubmit = e => {
e.preventDefault();
const data = JSON.stringify({
parameters: {
startTime: this.state.date,
selectors: this.state.selectors,
offset: this.state.offset,
"length.seconds": this.state.lengthSeconds,
"runtime.seconds": !this.state.checked
? this.state.runtimeSeconds
: undefined
}
});
console.log(data);
};
所以通常这会将表单状态中的数据发送到我指定的 URL。
假设我想将此数据放入表单状态,而不是提交,而是将其写入文件。
handleSave = e => {
e.preventDefault();
const data = JSON.stringify({
parameters: {
startTime: this.state.date,
selectors: this.state.selectors,
offset: this.state.offset,
"length.seconds": this.state.lengthSeconds,
"runtime.seconds": !this.state.checked
? this.state.runtimeSeconds
: undefined
}
});
// write data to csv file here.
};
这可能吗?是否有特定的库在这里有帮助?
我有一个 codesandbox这里有我的组件和表单的更大演示
最佳答案
您可以在handleSave
函数中调用以下函数:
function download(filename, text){
var blob = new Blob([text], {type: "text/plain"});
var url = window.URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = url;
a.download = filename;
a.click();
}
download("text.txt", "file contents here...");
此处的 MIME 类型列表:https://www.freeformatter.com/mime-types-list.html#mime-types-list
关于javascript - React - 将表单数据写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55127865/