簡體   English   中英

在 React 中使用鍵盤的向上/向下箭頭鍵滾動?

[英]Scroll with keyboard's up/down arrows keys in React?

我有一個自定義列表框,一個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都有一個點擊事件處理程序this.handleClick(targetDetailsData, todo.aprReference, index)

在此處輸入圖片說明

這可以通過在 ReactJS 中使用ref ,然后為keydown事件添加一個事件偵聽器,然后將焦點移動到下一個或上一個同級來完成。

筆記

  • 我將tabindex屬性添加到每個 div 以允許它們專注於
  • 我在包裝元素上使用ref來監聽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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM