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
相关产品推荐
相关产品推荐

