【问题标题】:(React.js) Scroll through list using arrow keys(React.js) 使用箭头键滚动列表
【发布时间】:2020-05-22 01:12:14
【问题描述】:

我正在开发一个自动完成组件,但我无法使用箭头键(向下/向上)滚动,使用鼠标它可以正常工作。

image

我对此进行了很多研究,并试图用 refs 解决这个问题,但没有奏效。

const refs = filteredSuggestions.reduce((acc, value) => {
  acc[value.id] = React.createRef();
  return acc;
}, {});

引用的地方

suggestionsListComponent = (
   <ul class="suggestions">
        {filteredSuggestions.map((suggestion, index) => {
          let className;
          if (index === activeSuggestion) {
            className = "suggestion-active";
          }
          return (
            <li ref={refs[suggestion.id]} className={className} key={suggestion} onClick={onClick}>
              {suggestion}
            </li>
          );
        })}
   </ul>
);

完整代码在这里:codesandbox

谁能帮我解决这个问题?

【问题讨论】:

    标签: javascript reactjs scroll autocomplete arrow-keys


    【解决方案1】:

    使用与 swipe-reactwheel-react 包中使用的相同配置,轻松地将您的 react 组件与键盘箭头键集成。

    用法

    1. 安装 npm 包:

      npm install --save arrow-keys-react
      
    2. 导入:

      import ArrowKeysReact from 'arrow-keys-react';
      
    3. 在组件构造函数或渲染函数中配置箭头键事件('left'、'right'、'up'、'down'),至少其中一个:

      ArrowKeysReact.config({
        left: () => {
         console.log('left key detected.');
       },
       right: () => {
         console.log('right key detected.');
       },
       up: () => {
         console.log('up key detected.');
       },
       down: () => {
         console.log('down key detected.');
       }
      });
      

    4.与你的 React 组件集成:

    <YourComponent {...ArrowKeysReact.events} />
    

    示例

    import React, { Component } from 'react';
    import ArrowKeysReact from 'arrow-keys-react';
    
    class App extends Component {
     constructor(props){
      super(props);
      this.state = {
       content: 'Use arrow keys on your keyboard!'
     };
     ArrowKeysReact.config({
      left: () => {
        this.setState({
          content: 'left key detected.'
        });
      },
      right: () => {
        this.setState({
          content: 'right key detected.'
        });
      },
      up: () => {
        this.setState({
          content: 'up key detected.'
        });
      },
      down: () => {
        this.setState({
          content: 'down key detected.'
        });
      }
     });
    }
    render() {
    return (
      <div {...ArrowKeysReact.events} tabIndex="1">
        {this.state.content}
      </div>
      );
      }
     }
    
    export default App;
    

    备注

    • 使用div时,添加tabIndex属性。
    • 元素必须在焦点上才能检测箭头键。当用户单击元素或使用键盘中的 tab 键聚焦它时,将检测到箭头键。或者,您可以在加载时将组件编程为 focus()
    • ArrowKeysReact.config 可以放在 render 函数中而不是 constructor 函数中。

    【讨论】:

    猜你喜欢
    • 2015-06-11
    • 2012-02-06
    • 2021-10-19
    • 2011-05-16
    • 2011-03-13
    • 1970-01-01
    • 2012-01-16
    • 1970-01-01
    • 2010-11-11
    相关资源
    最近更新 更多