[英]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.