问题描述
我在提交表单时遇到了 react hook 表单和 material-ui 文件上传的问题,我得到了一个文件的字符串路径而不是 FileList 实例
<Controller
name='attachments'
control={control}
defaultValue=''
render={({ field }) => <input {...field} type='file' multiple />}
/>
https://codesandbox.io/s/xenodochial-bhaskara-9vo13?file=/src/App.js
解决方法
要使其正常工作,您必须实现自己的 onChange
属性。为此,您可以使用 field.onChange
回调并将文件列表作为参数传递给它。实现方法如下:
<Controller
name="attachments"
control={control}
defaultValue=""
render={({ field }) => (
<input
type="file"
onChange={e => {
field.onChange(e.target.files);
}}
multiple
/>
)}
/>