React-Hook-Form多文件字段的TypeScript类型定义咨询
React Hook Form 多文件字段的 TypeScript 类型指定
对于开启multiple的文件上传字段,你需要给files指定File[]类型;如果要兼容未选择文件的空状态,推荐使用File[] | undefined,这样类型检查会更严谨。
原因是:当用户通过<input type="file" multiple />选择文件后,React Hook Form会自动将选中的文件解析为File对象组成的数组;若用户未选择任何文件,该字段的初始值会是undefined。
修改后的类型定义和代码如下:
import * as React from "react"; import { useForm } from "react-hook-form"; type FormData = { firstName: string; lastName: string; files: File[] | undefined; // 这里指定正确类型 }; export default function App() { const { register, setValue, handleSubmit, formState: { errors } } = useForm<FormData>(); const onSubmit = handleSubmit(data => console.log(data)); return ( <form onSubmit={onSubmit}> <label>First Name</label> <input {...register("firstName")} /> <label>Last Name</label> <input {...register("lastName")} /> <label>Files</label> <input type="file" multiple {...register("files")} /> <button type="button" onClick={() => { setValue("lastName", "luo"); // ✅ setValue("firstName", true); // ❌: true 不是 string 类型 errors.bill; // ❌: bill 属性不存在 }} > SetValue </button> </form> ); }
内容的提问来源于stack exchange,提问作者thiras
相关产品推荐
相关产品推荐

