HandleKeyPress无法识别向下箭头。

7
我正在使用React.js构建一个定制的、可访问的输入框中

您正在混合使用不同的KeyboardEvent属性。您可以在此处查看不同类型键盘事件的不同属性及其值:https://keyjs.dev - Danziger
2个回答

9

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'。此外,请查看 https://keyjs.dev。我很快会添加有关这些跨浏览器不兼容性的信息! - Danziger

5
对于箭头键,我认为您需要使用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>


1
请注意,一些旧浏览器使用了一些非标准代码。例如,左箭头通常是 'LeftArrow',右箭头是 'RightArrow',但在 IE 和 Legacy Edge 中,它们将显示为 'Left''Right'。此外,请查看 https://keyjs.dev。我很快会添加有关这些跨浏览器不兼容性的信息! - Danziger

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接