如何使用 useForm 钩子获取输入值,然后使用 json-server 执行 POST?

How can i get an input value with useForm hook and then perform a POST with json-server?

我是 ReactJs 的新手,正在尝试使用 json-server 在假 API 中创建 CRUD。我如何正确使用 useForm Hook 并执行 POST 用户名和电子邮件?

import React from "react";
import { useForm } from "react-hook-form";

import Form from "../Form";
import Field from "../Field";
import Button from "../Button";

const FormNew = () => {
  const { register, handleSubmit } = useForm();

  const newUser = (user) => {
    console.log(user);
    const url = "http://localhost:3002/posts";
    fetch(url, {
      method: "POST",
      headers: {
        "Content-type": "application/json",
      },
      body: JSON.stringify({
        name: "example-name",
        email: "example@mail.com",
      }),
    })
      .then((resp) => resp.json())
      .then((user) => {
        console.log("User created success", user);
      });
  };

  return (
    <Form onSubmit={handleSubmit(newUser)}>
      <Field.Text label="Name" name="name" type="text" {...register} />
      <Field.Text label="Email" name="email" type="email" {...register} />
      <Button>Submit</Button>
    </Form>
  );
};
export default FormNew;

您必须在您的 组件上注册您的价值键

<Form onSubmit={handleSubmit(newUser)}>
  <Field.Text label="Name" name="name" type="text" {...register('name')} />
  <Field.Text label="Email" name="email" type="email" {...register('email')} />
  <Button>Submit</Button>
</Form>