简体   繁体   English

反应隐藏的输入类型文件 onChange 不触发

[英]React hidden input type file onChange not firing

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>
)

So basically the file choosing window is showing but after I choose a pic the "handleProfilePicUpload" is not firing.所以基本上选择 window 的文件正在显示,但在我选择图片后,“handleProfilePicUpload”没有触发。

You trying to simulate onChange by click event.您试图通过click事件来模拟onChange Change the listener to onClick :将监听器更改为onClick

<input onClick={handleProfilePicUpload} .. />

A cleaner solution would be using a label:更清洁的解决方案是使用 label:

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

You can simply use a label:您可以简单地使用 label:

 .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>

It will work exactly as an HTML file input tag works.它将与 HTML 文件input标签的工作方式完全相同。

So, you can do:所以,你可以这样做:


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}
/>
<input
   type="file"
   accept="image/*"
   name="pic"
   onChange={(e: any) => {}}
   style={{ display: 'none' }}
   ref={fileRef}
/>

If you hide the input through styles onChange does get fired but make sure your component is mounted before your call click through the reference如果您通过 styles 隐藏输入,onChange 确实会被触发,但请确保您的组件在调用之前已安装,请点击参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM