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

TypeScript下React+Node.js使用react-hook-form上传PDF的ref类型错误求助

问题排查与解决方案

报错原因

  • 你使用的是react-hook-form v7及以上版本,该版本对register方法的API做了破坏性变更:不再支持直接将register函数赋值给ref属性,而是需要调用register(字段名)后,将返回的所有属性展开绑定到表单元素上。
  • 缺少表单字段的TS类型定义,导致类型校验不通过。

修复后的完整代码

import React from 'react';
import { useForm, SubmitHandler } from 'react-hook-form';
import './Bind.scss';

// 定义表单字段类型
type FormInputs = {
  picture: FileList
}

export const Bind = () => {
  // 给useForm传入泛型定义字段类型
  const { register, handleSubmit } = useForm<FormInputs>();

  const onSubmit: SubmitHandler<FormInputs> = async (data) => {
    const formData = new FormData();
    formData.append('picture', data.picture[0]);
    const res = await fetch('http://localhost:4000/picture', {
      method: 'POST',
      body: formData,
    }).then((res) => res.json());
    alert(JSON.stringify(res));
  };

  function download(blob: Blob, filename: string) {
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
  }

  const loadFile = async () => {
    const encodedValue = encodeURIComponent('mobx-bf.png');
    await fetch(`http://localhost:4000/getPdf/?fileToDownload=${encodedValue}`)
      .then((res) => res.blob())
      .then((blob) => download(blob, 'mobx-bf.png'));
  };

  return (
    <div>
      <form onSubmit={handleSubmit(onSubmit)}>
        {/* 核心修改:调用register传入字段名,展开返回的所有属性,不需要单独写name和ref */}
        <input {...register('picture')} type="file" />
        <button type="submit">Submit</button>
      </form>
      <button onClick={loadFile}>Load</button>
    </div>
  );
};

关键修改点说明

  • 给useForm传入泛型FormInputs,明确表单内picture字段的类型是FileList,解决TS类型报错
  • 将原来的<input ref={register} type="file" name="picture" />改为<input {...register('picture')} type="file" />,符合v7版本的API使用规范,register调用后会自动绑定name、ref、事件处理函数等所需属性
  • 补充了onSubmit、download等函数的参数类型,避免隐式any报错
  • 优化了loadFile的异步调用逻辑,避免回调嵌套问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 18:36:07