【问题标题】:HandleKeyPress not recognising down arrowHandleKeyPress 无法识别向下箭头
【发布时间】:2019-02-19 17:38:18
【问题描述】:

我正在使用 React.js 构建一个定制的、可访问的 select 输入。我需要使updown 箭头键功能,因为tab 键将在select 输入的options 范围内。

我在元素上有一个 handleKeyPress 函数,用于检测何时按下其他键(例如 'Enter' 工作正常)。

这是一个例子option

<li
  className="oc-select-field__item"
  tabIndex="0"
  onClick={handleClick}
  onKeyPress={handleKeyPress}
>

...这里是handleKeyPress 函数

handleKeyPress = event => {
  if (event.key === 40) {
    console.log('Down arrow key fired'); // does not fire
  }
  if (event.key === 'Enter') {
    console.log('Enter key fired'); // does fire
  }
};

当按下down 箭头时我没有成功检测到我做错了什么?

【问题讨论】:

  • 您正在混合不同的KeyboardEvent 属性。您可以在此处查看不同类型的键盘事件的不同属性及其值:keyjs.dev

标签: javascript reactjs select accessibility


【解决方案1】:

event.which 会给你密钥的数值。

event.keyevent.code 会给你一个字符串值。

试试这个工具:http://keycode.info

if (event.key === 'ArrowDown') {
    console.log('Down arrow key fired');
}

正如@devserkan 所说,您应该使用onKeyDown 而不是onKeyPress

keydown 事件在按下某个键时触发。与 keypress 事件不同,keydown 事件会针对产生字符值的键和不产生字符值的键触发。

【讨论】:

  • 请记住一些旧浏览器使用了一些非标准代码,例如,左边通常是'LeftArrow',右边是'RightArrow',但在 IE 和 Legacy Edge 上它们会显示为'Left''Right' 代替。另外,请查看keyjs.dev。我将很快添加有关这些跨浏览器不兼容性的信息! ?
【解决方案2】:

对于箭头键,我认为您需要onKeyDown 而不是onKeyPress

class App extends React.Component {
  handleKeyPress = ( event ) => {
    if ( event.key === "ArrowDown" ) {
      console.log( "Down arrow key fired" ); // does not fire
    }
    if ( event.key === "Enter" ) {
      console.log( "Enter key fired" ); // does fire
    }
  };

  render() {
    return (
      <div>
        <ul>
          <li
            tabIndex="0"
            onClick={this.handleClick}
            onKeyDown={this.handleKeyPress}
          >Foo
          </li>
        </ul>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

【讨论】:

  • 请记住,一些旧浏览器使用了一些非标准代码,例如,左边通常是'LeftArrow',右边是'RightArrow',但在 IE 和 Legacy Edge 上它们会显示为'Left''Right' 代替。另外,请查看keyjs.dev。我将很快添加有关这些跨浏览器不兼容性的信息! ?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-18
  • 1970-01-01
  • 2014-07-16
  • 1970-01-01
  • 2019-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多