简体   繁体   English

无法使用键盘从 label 元素触发输入事件

[英]Unable to trigger input event from label element with keyboard

When I click the label with the mouse I get the file browser popup as expected.当我用鼠标单击label时,我得到了预期的文件浏览器弹出窗口。 But when I use the keyboard and tab to the label and hit enter I don't.但是当我使用键盘和Tab键输入 label 并按回车键时,我没有。

<>
  <label className="button" htmlFor="fileUploadInput" tabIndex={0}>
    Upload File
  </label>
  <input id="fileUploadInput" type="file" onChange={handleChange} />
</>

To create a custom file input button, the label has all the fancy styling and is visible.要创建自定义文件输入按钮, label具有所有奇特的样式并且是可见的。 The input has the style below. input具有以下样式。

input {
  visibility: hidden;
  height: 0;
  width: 0;
}

As mentioned in the comments there is no native way to handle this.正如评论中提到的,没有本地方法来处理这个问题。 I ended up creating a ref for the input .我最终为input创建了一个ref And added a onKeyUp event on the label which allowed to programmaticly open the file browser dialog when the enter key was clicked.并在label上添加了一个onKeyUp事件,允许在单击回车键时以编程方式打开文件浏览器对话框。

const inputRef = useRef(null);

const handleLabel = (e) => {
  if (e.key !== "Enter" || inputRef.current === null) return;
  inputRef.current.click();
};

<>
  <label
    className="button"
    htmlFor="fileUploadInput"
    tabIndex={0}
    onKeyUp={handleLabel}
  >
    Upload File
  </label>
  <input
    ref={inputRef}
    id="fileUploadInput"
    type="file"
    onChange={handleChange}
  />
</>

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

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