英文:
Why can't I hide my input field where the type is a file type
问题
我尝试隐藏文件类型的输入字段,但尽管具有隐藏属性,它仍然无法隐藏自己。
但是,当我移除 type="file" 后,代码会正确隐藏自己。
请问是否有人知道我是否可以隐藏带有 type="file" 的文件?谢谢!
英文:
I am trying to hide my input field of a file type, however despite having the hidden attribute it will not hide itself.
However, after I remove type="file", the code will hide itself properly
May I know if anyone knows if I can hide the file with type="file"? Thank you !
答案1
得分: 1
hidden
和 type="file"
是相同的属性。如果你定义了 hidden
属性,就不能使用文件上传,或者定义了 type='file'
,就不能将这个元素隐藏起来。为了解决这个问题,你必须使用内联样式 display: 'none'
来隐藏这个元素,并设置 type="file"
属性而不使用 hidden
。
首先,声明用于 input 元素标签的 ref。
const uploadRef = useRef()
然后调用 uploadRef.current.click()
来显示上传文件窗口。
代码示例
const FileUpload = () => {
const uploadRef = useRef(null)
const onSelectFile = e => {
const file = e.target.files[0]
if (!file) {
console.log('未选择文件')
return
}
console.log(file)
console.log(file.name)
}
return (
<div>
<input ref={uploadRef} type='file' style={{display:'none'}} onChange={onSelectFile}/>
<button type='button' onClick={() => uploadRef.current.click()}>上传文件</button>
</div>
)
}
英文:
The hidden
and type="file"
are the same attribute. If you either define attribute hidden
, you cannot use file upload, or define type='file'
, you cannot make this element hidden. To solve the problem, you must use inline styling display: 'none'
to hide this element and set the attribute type="file"
without hidden
.
First, declare ref for using with input element tag.
const uploadRef = useRef()
Then call the uploadRef.current.click()
for show upload file window.
Code example
const FileUpload = () => {
const uploadRef = useRef(null)
const onSelectFile = e => {
const file = e.target.files[0]
if (!file) {
console.log('No file selected')
return
}
console.log(file)
console.log(file.name)
}
return (
<div>
<input ref={uploadRef} type='file' style={{display:'none'}} onChange={onSelectFile}/>
<button type='button' onClick={()=>uploadRef.current.click()}>Upload File</button>
</div>
)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论