我正在尝试引用一个输入文件<Control.file/>元素到另一个风格良好的元素,即使在谷歌上搜索后我也没有找到答案,所以我在这里满怀希望地得到答案。
这是我的redux控制表单的一部分,并使用Ref钩子:
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输入时,如<输入类型=";文件"/>它运行良好,但当我提交表单并将其更改为<Control.file/>当我点击span元素时,我收到一条错误消息,上面写着:类型错误:fileInput.current.click不是一个函数。
我试过
<span onClick={((=>fileInput.current.props.onChange((}}/>
然后事件变得未定义:
TypeError:无法读取未定义的属性"preventDefault">
console.log(事件(//未定义
而不是
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