React+Inertia.js中useForm无法设置File字段问题求助
问题解决:Inertia.js + React 中文件无法通过useForm设置的问题
核心问题
你遇到的问题根源在于给file类型的input绑定了value={data.file},以及一处代码笔误:
- File类型的input是特殊受控组件,不能直接将File对象赋值给
value属性——这会导致React无法正确跟踪文件选中状态,进而让useForm的setData无法更新file字段。 - 代码中
setFile(null)是未定义的函数,属于笔误。
修复步骤
1. 移除input的value绑定
修改文件输入框代码,删掉value={data.file}:
<input type="file" id="document_pdf" name="file" accept=".pdf,application/pdf" className="mt-1 block w-full" onChange={handleFileChange} />
2. 修正笔误
把handleFileChange里的setFile(null)改成setData('file', null):
const handleFileChange = (e) => { const file = e.target.files[0]; console.log(file); if (file && file.type === 'application/pdf') { setData('file', file); setData('filename', file.name); console.log("File attached"); } else { // 修正此处笔误 setData('file', null); setData('filename', ''); console.log("No file attached"); } };
3. 提交表单(无需手动创建FormData)
Inertia的useForm会自动识别File对象,提交时自动转为multipart/form-data请求,直接调用post方法即可:
const handleSubmit = () => { post('/your-submit-url'); };
验证
修改完成后,点击调试按钮查看data.file,应该能正常显示选中的File对象,提交表单时后端也能接收到文件。
内容的提问来源于stack exchange,提问作者ClockworkOnion
相关产品推荐
相关产品推荐

