【问题标题】:React hidden input type file onChange not firing反应隐藏的输入类型文件 onChange 不触发
【发布时间】:2021-05-10 15:05:48
【问题描述】:
const passFromPicToUpload = (e) =>{
        hiddenFileInput.current.click();
        console.log("one")
    }

const handleProfilePicUpload = (e) =>{
    console.log("two")

    if(e.target.files[0]){
        setImage(e.target.files[0]);
        
    }
}

 return (
     <div className="profile">
      <div className="imageContainer" >
       <a href="#" onClick={passFromPicToUpload}>
        {
          profile.avatarUrl?<Image src={profile.avatarUrl} className="profile__image"  /> :<Image src="https://i.stack.imgur.com/l60Hf.png" className="profile__image" /> 
        }
       </a>
      </div>   
     <input type="file" ref={hiddenFileInput} onChange={handleProfilePicUpload} style={{display:'none'}} /> 

 </div>
)

所以基本上文件选择窗口正在显示,但是在我选择图片后,“handleProfilePicUpload”没有触发。

【问题讨论】:

  • 请向我们展示整个组件。另外,为什么是“显示:无”?
  • 你为什么不直接使用label
  • 以下答案对您有帮助吗?如果有,请accept or vote

标签: javascript reactjs


【解决方案1】:

您试图通过click 事件模拟onChange。将监听器改为onClick

<input onClick={handleProfilePicUpload} .. />

更清洁的解决方案是使用标签:

<input type="file" id="file" style="display:none;">
<label for="file">
   <a>Image</a>
</label>

【讨论】:

    【解决方案2】:

    您可以简单地使用标签:

    .hidden {
      display: none;
    }
    <input type="file" name="file" id="my-file" class="hidden">
    <label for="my-file">
       <img src="https://picsum.photos/200/300" width="100" height="100"> 
    </label>

    它的工作原理与 HTML 文件 input 标签的工作原理完全相同。

    所以,你可以这样做:

    
    function onFileChange(e) {
      setImage(e.target.files)
    }
    
    // ...
    
    <label
      htmlFor="my-file"
      title="Click to choose a file"
    >
      <img src="https://picsum.photos/200/300" width="100" height="100">
    </label>
    <input
      type="file"
      id="my-file"
      className="hidden"
      onChange={onFileChange}
    />
    

    【讨论】:

      猜你喜欢
      • 2018-10-22
      • 1970-01-01
      • 2011-10-24
      • 2021-12-30
      • 1970-01-01
      • 2017-06-03
      • 2016-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多