为什么我不能隐藏输入字段,类型为文件类型?

huangapple go评论52阅读模式
英文:

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

hiddentype="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=&quot;file&quot; are the same attribute. If you either define attribute hidden, you cannot use file upload, or define type=&#39;file&#39;, you cannot make this element hidden. To solve the problem, you must use inline styling display: &#39;none&#39; to hide this element and set the attribute type=&quot;file&quot; 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 = () =&gt; {
  const uploadRef = useRef(null)
  
  const onSelectFile = e =&gt; {
    const file = e.target.files[0]
    if (!file) {
      console.log(&#39;No file selected&#39;)
      return
    }
    console.log(file)
    console.log(file.name)
  }

  return (
    &lt;div&gt;
      &lt;input ref={uploadRef} type=&#39;file&#39; style={{display:&#39;none&#39;}} onChange={onSelectFile}/&gt;
      &lt;button type=&#39;button&#39; onClick={()=&gt;uploadRef.current.click()}&gt;Upload File&lt;/button&gt;
    &lt;/div&gt;
  )
}

huangapple
  • 本文由 发表于 2023年2月16日 11:13:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75467488.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定