You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

react-hook-form使用时报错handleSubmit is not a function如何解决?

报错原因与修复方案

核心问题点

  • react-hook-form v7版本对register API做了破坏性更新,不再支持直接作为ref传入输入框,必须调用register(字段名)将返回的属性绑定到输入框上,错误的register用法会导致useForm初始化异常,返回对象中的handleSubmit不是可执行函数。
  • handleSubmit已经内部封装了阻止表单默认提交行为的逻辑,你定义的onSubmit回调第一个参数会直接接收到表单数据,不需要自行处理e.preventDefault(),也不需要接收事件对象作为参数。
  • axios的POST请求方法为小写axios.post,大写写法不存在,会额外触发报错。

修正后完整代码

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 = (data) => {
        console.log(data);
        addReview(data);
    }

    const addReview = (data) => {
        // post改为小写
        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)}>
                {/* 给每个输入框指定字段名,调用register绑定属性 */}
                <input type="text" placeholder="Book Title" {...register('title')} />
                <input type="text" placeholder="Rating" {...register('rating')} />
                <input type="text" placeholder="Review" {...register('review')} />
                <input type="submit" value="提交评论" />
             </form>
        </Style>
    )
};

export default Add;

内容的提问来源于stack exchange,提问作者GDelsaux

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 02:36:03