使用 React 将提交的表单值保存在 JSON 文件中

CJN*_*tts 2 javascript forms json reactjs

我正在尝试在 React 中创建一个表单,它将在提交时使用表单中的值更新 JSON 文件。(最终结果是,每次提交表单时,这将在 JSON 文件中创建一个数据数组,然后可用于在应用程序的其他地方填充提交结果的“列表”)

表单本身工作正常,但每次我按提交时都会收到错误消息:“TypeError: fs.writeFile is not a function”

import React, { Component } from "react";
import { Form, Button } from 'semantic-ui-react';
import jsonfile from'jsonfile';

var file = 'data.json'

var obj = {name: 'JP'}


export default class App extends Component {
  constructor(props) {
    super(props)

    this.state = {
      name: "",
      email: ""
    }

    this.handleChange = this.handleChange.bind(this);
    this.sendDataSomewhere = this.sendDataSomewhere.bind(this);
}


handleChange = (e, {name, value}) => {
  this.setState({[name]: value})
}

sendDataSomewhere = function jsonfile(file){
jsonfile.writeFile(file, obj, function (err) {
  console.error(err);
});
};

  render() {
    return (
     <div>
      <Form onSubmit={this.sendDataSomewhere}>
        <Form.Field>
          <Form.Input name="name" value={this.state.name} onChange={this.handleChange}/>
        </Form.Field>
        <Form.Field>
          <Form.Input name="email" value={this.state.email} onChange={this.handleChange}/>
        </Form.Field>
        <Button type="submit">Submit</Button>
       </Form>
     </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

如果有人能让我知道我做错了什么或提供类似的例子,我将不胜感激。

谢谢

小智 7

客户端解决方案是:

const handleSaveToPC = (jsonData,filename) => {
  const fileData = JSON.stringify(jsonData);
  const blob = new Blob([fileData], {type: "text/plain"});
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.download = `${filename}.json`;
  link.href = url;
  link.click();
}
Run Code Online (Sandbox Code Playgroud)