最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React File input not opening file browser - Stack Overflow

programmeradmin4浏览0评论

I am encountering a very strange error in my React application. I have this code:

<input
  accept="image/*"
  onChange={doUpload}
  type="file"
  name="fileUploader"
  id="photoUploader"
  ref={fileRef}
/>

but when I click the input to select a file, I don't get the file explorer at all. I also noticed that some of my form's onSumit did not fire until I added an onClick handler to the submit button.

I am encountering a very strange error in my React application. I have this code:

<input
  accept="image/*"
  onChange={doUpload}
  type="file"
  name="fileUploader"
  id="photoUploader"
  ref={fileRef}
/>

but when I click the input to select a file, I don't get the file explorer at all. I also noticed that some of my form's onSumit did not fire until I added an onClick handler to the submit button.

Share Improve this question edited Sep 5, 2020 at 8:44 halfer 20.4k19 gold badges109 silver badges202 bronze badges asked Aug 27, 2019 at 10:55 KenshinmanKenshinman 7519 silver badges23 bronze badges 2
  • what is the value in {fileRef}. Try with just ref="upload" and see if issue happens. – Mahendra Pratap Commented Aug 27, 2019 at 11:00
  • add this. before doUpload – Alex Commented Aug 27, 2019 at 11:37
Add a ment  | 

3 Answers 3

Reset to default 12

Wow, found the bug. I had an event.stopPropagation() somewhere in a nested ponent.

I had the same issue, dont know why it is was happening but I did in this way

const fn = useCallback((event) => {
    console.log("clicked");
    event.stopPropagation();
}, []);


const handleFileClick = (event) => {
    if (fileRef.current) {
        fileRef.current.addEventListener("click", fn);
        fileRef.current.click();
    }
};

You have to add this keyword. I hope it is useful for you:

       <input
          accept="image/*"
          onChange={this.doUpload}
          type="file"
          name="fileUploader"
          id="photoUploader"
          ref={this.fileRef}
        />
发布评论

评论列表(0)

  1. 暂无评论