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

React Hook Form配合Material UI TextField文件上传onSubmit无法获取FileList

报错原因

报错核心是因为{...field}透传时,把react-hook-form维护的value值也传给了TextField,而type为file的input元素的value属性是只读属性,仅允许用户通过本地选择文件操作修改,不支持代码手动赋值,因此触发了Failed to set the 'value' property on 'HTMLInputElement'错误。

解决方案

仅需要在解构field时把value属性单独剥离,不传递给TextField即可,修改后的代码如下:

<Controller
  name="photo"
  control={control}
  render={({ field: { ref, value, onChange, ...field } }) => (
    <TextField
      {...field}
      inputRef={ref}
      fullWidth
      label="photo"
      margin="dense"
      accept="image/*"
      type="file"
      error={!!errors.photo}
      onChange={(event) => {
        onChange(event.target.files);
      }}
      InputLabelProps={{
        shrink: true,
      }}
    />
  )}
/>

补充说明

如果需要支持多文件上传,给TextField增加inputProps={{ multiple: true }}属性即可,提交时拿到的photo字段就是完整的FileList对象,取单文件可直接访问photo[0]。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 07:00:03