如何解决如何将ref用于“输入文件”与react redux-form受控形式
我正在尝试将输入文件
这是我的 redux 控制表单和 useRef 钩子的一部分:
const fileInput = useRef(null);
<Form model="testimonial" onSubmit={(value) => handleSubmit(value)}>
<div id="preview-upload" className="form-group">
<span onClick={() => {console.log(fileInput.current); fileInput.current.click()}} ></span>
<Control.file ref={fileInput} onChange={(e) => handleImgPreview(e)} model=".photo" name="photo" id="photo" />
</div>
</Form>
这是 onChange 会被执行的函数
const handleImgPreview = (event) =>{
console.log(event)
event.preventDefault();
let reader = new FileReader();
let file = event.target.files[0];
reader.onloadend = () => {
setImgPrev({...imgPrev,file: file,imgurl: reader.result})
}
reader.readAsDataURL(file)
};
当我更改为像 这样的普通 HTML 输入时,它工作正常,但当然我在提交表单时遇到了问题当我将其更改为
我试过了
fileInput.current.props.onChange()}} />
然后事件变得未定义:
TypeError: 无法读取未定义的属性“preventDefault”
console.log(event) // 未定义
解决方法
代替
ref={fileInput}
使用
getRef={(input) => fileInput = input}
并注意 getRef prop accept 函数,它调用节点实例提供给它的回调。
现在,如果你控制台 fileInput 你会得到 多亏了 getRef 中的回调函数,因此你不必访问 .current,只需在 iputFile 之后调用 click() 方法,如图所示下面:
<span onClick={() => {console.log(fileInput); fileInput.click()}}></span>
<Control.file getRef={(input) => fileInput = input} onChange={(e) => handleImgPreview(e)} model=".photo" name="photo" id="photo" />
更多信息:
https://davidkpiano.github.io/react-redux-form/docs/api/Control.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。