react-hook-form:handleSubmit 不是函数

react-hook-form: handleSubmit is not a function

我想使用 react-hook-form 来处理来自用户的输入。 React 给我一个错误,说“handleSubmit 不是一个函数”。任何帮助将不胜感激。

我的代码如下(react-hook-form 7.13.0)

import { useForm } from "react-hook-form";
import axios from "axios";
import styled from "styled-components";

const Style = styled.div`
    .form {
        width: 200px;
        display: flex;
        flex-direction: column;
    }
`;

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

    const onSubmit = (e, data) => {
        e.preventDefault();
        console.log(data);
        addReview(data);
    }

    const addReview = (data) => {
        axios.POST("http://localhost:3000/reviews", data).then(() => {
            props.setReviews([...props.reviews, {data}])
        })
    }
    return (
        <Style>
            <h3>Add a review</h3>
            <form className="form" onSubmit={handleSubmit(onSubmit)}>
                <input type="text" placeholder="Book Title" ref={register}></input>
                <input type="text" placeholder="Rating" ref={register}></input>
                <input type="text" placeholder="Review" ref={register}></input>
                <input type="submit" placeholder="Review"></input>
             </form>
        </Style>
    )
};

export default Add;

你打错了。

这是您目前拥有的:

<form className="form" onSubmit={handleSubmit(onSubmit)}>

您调用了 handleSubmit(onSubmit),但我猜您正在尝试使用 onSubmit 作为处理程序。将上面的行替换为:

<form className="form" onSubmit={onSubmit}>

你能试试这个吗...

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

  const onSubmit = (data) => {
    console.log(data);
    addReview(data);
  };

  const addReview = (data) => {
    axios.POST("http://localhost:3000/reviews", data).then(() => {
      props.setReviews([...props.reviews, { data }]);
    });
  };
  return (
    <Style>
      <h3>Add a review</h3>
      <form className="form" onSubmit={handleSubmit(onSubmit)}>
        <input
          type="text"
          placeholder="Book Title"
          {...register("bookTitle")}
        ></input>
        <input type="text" placeholder="Rating" {...register("rating")}></input>
        <input type="text" placeholder="Review" {...register("review")}></input>
        <input type="submit" placeholder="Review"></input>
      </form>
    </Style>
  );
};

为每个 input 传递此 name 以便注册:

{...register("rating")}

参考:https://react-hook-form.com/api/useform/register

You have to register your input into the hook by invoking the "register" function

像这样<input type="text" placeholder="Rating" {...register("Rating")}></input>