【问题标题】:Press and hold arrow keys to scroll in grid in react按住箭头键在反应中滚动网格
【发布时间】:2021-09-12 20:04:01
【问题描述】:

采用以下 React (17.0.2) 组件:

const Grid = () => {
     return (
          <div id='grid' style={{display: 'flex', flexDirection: 'column'}}>
               <div style={{display: 'flex'}}>
                   <div>
                       1
                   </div>
                   <div>
                       2
                   </div>
                   <div>
                       3
                   </div>
               </div>
               <div style={{display: 'flex'}}>
                   <div>
                       4
                   </div>
                   <div>
                       5
                   </div>
                   <div>
                       6
                   </div>
               </div>
               <div style={{display: 'flex'}}>
                   <div>
                       7
                   </div>
                   <div>
                       8
                   </div>
                   <div>
                       9
                   </div>
               </div>
          </div>

     )
}

这只是一个带有一些简单数据的简单网格。向其中添加事件侦听器很容易,如果您点击它们,您可以使用箭头键滚动。如何让它按住箭头键会不断滚动?

到目前为止,我尝试过的主要事情是:

  1. 将所选单元格保存为 React 状态。
  2. 在 keydown 事件中,设置一个间隔,使所选单元格朝正确的方向移动。
  3. keyup 事件时,清除此间隔

这样的问题是它确实不一致 - 间隔只是有时被清除,有时滚动只是继续!

如果您可以使网格变大,则可以加分,然后将滚动的元素保留在视口中!

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 您使用的是哪个反应版本?它将帮助我们更有效地提出建议代码
  • @RobertCorponoi 更新了我到目前为止所尝试的内容。
  • @hai-thai 在顶部也更新了 react 版本!

标签: javascript html reactjs scroll dom-events


【解决方案1】:

这很简单 - 使用 ref 处理当前元素焦点和用户按下 keydown

const myRef = useRef();

useEffect(() => {
    const node = myRef.current;
    node.addEventListener('keydown',(e) => {
      const active = document.activeElement;
      if(e.keyCode === 40 && active.nextSibling) {
        active.nextSibling.focus();
      }
      if(e.keyCode === 38 && active.previousSibling) {
        active.previousSibling.focus();
      }
    });

} , [])

<div id='grid' ref={myRef} style={{display: 'flex', flexDirection: 'column'}}>

【讨论】:

  • 酷!所以我缺少的是,如果你按住键,就会重复触发一个 keydown 事件。有帮助。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-27
  • 2011-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-06
  • 2014-08-10
相关资源
最近更新 更多