在 React 中使用键盘的向上/向下箭头键滚动?

IT技术 javascript reactjs keyboard-events
2021-05-24 19:35:27

我有一个自定义列表框,div其中包含其他div孩子的垂直列表我想添加一个向上/向下箭头键导航来更改当前选择的子项。

因此,当我单击第一项并按 时down arrow key,它应该允许我选择第二项(下一项)。如果我单击up arrow key,它应该选择回第一项(上一项)。

const renderInboxSummary = targetDetailsData.map((todo, index) => {
  const hasNewMessageInd = todo.hasNewMessageInd;
  return (
   <div onClick={() => this.handleClick(targetDetailsData, todo.aprReference, index)}>
      <div>
        {todo.aprRecordUserName}
      </div>
      <div>
        {todo.aprBranchCode}
      </div>
      <div>
        {todo.aprScreeName}
      </div>
  </div>
  );
});

每个div都有一个 click 事件处理程序this.handleClick(targetDetailsData, todo.aprReference, index)

在此处输入图片说明

1个回答

这可以通过ref在 ReactJS 中使用 a 来完成,然后为该keydown事件添加一个事件侦听器,然后将焦点移动到下一个或上一个同级。

笔记

  • tabindex为每个 div添加属性以允许它们专注于
  • ref在包装元素上使用 a来监听keydown
  • 我检查keycode向上/向下移动到下一个/上一个兄弟姐妹
  • 我相信keycode全尺寸键盘上的向上/向下是不同的,但我没有要测试的。

解决方案

要测试演示,请单击任何 div,然后使用向上/向下箭头

const { Component } = React;

class App extends Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  componentDidMount() {
    this.moveFocus();
  }
  moveFocus() {
    const node = this.myRef.current;
    node.addEventListener('keydown', function(e) {
      const active = document.activeElement;
      if(e.keyCode === 40 && active.nextSibling) {
        active.nextSibling.focus();
      }
      if(e.keyCode === 38 && active.previousSibling) {
        active.previousSibling.focus();
      }
    });
  }
  render() {
    return (
      <div ref={this.myRef}>
        <div tabindex="0">First</div>
        <div tabindex="1">Second</div>
        <div tabindex="2">Third</div>
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
div:focus {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

文档

https://reactjs.org/docs/refs-and-the-dom.html

https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex