React: How to navigate through list by arrow keys

前端 未结 3 1654
耶瑟儿~
耶瑟儿~ 2020-12-07 13:47

I have build a simple component with a single text input and below of that a list (using semantic ui).

Now I would like to use the arrow keys to navigate through the

3条回答
  •  广开言路
    2020-12-07 14:02

    Try something like this:

    export default class Example extends Component {
      constructor(props) {
        super(props)
        this.handleKeyDown = this.handleKeyDown.bind(this)
        this.state = {
          cursor: 0,
          result: []
        }
      }
    
      handleKeyDown(e) {
        const { cursor, result } = this.state
        // arrow up/down button should select next/previous list element
        if (e.keyCode === 38 && cursor > 0) {
          this.setState( prevState => ({
            cursor: prevState.cursor - 1
          }))
        } else if (e.keyCode === 40 && cursor < result.length - 1) {
          this.setState( prevState => ({
            cursor: prevState.cursor + 1
          }))
        }
      }
    
      render() {
        const { cursor } = this.state
    
        return (
          
            
            
              {
                result.map((item, i) => (
                  
                    { item.title }
                  
                ))
              }
            
          
        )
      }
    }
    

    The cursor keeps track of your position in the list, so when the user presses the up or down arrow key you decrement/increment the cursor accordingly. The cursor should coincide with the array indices.

    You probably want onKeyDown for watching the arrow keys instead of onChange, so you don't have a delay or mess with your standard input editing behavior.

    In your render loop you just check the index against the cursor to see which one is active.

    If you are filtering the result set based on the input from the field, you can just reset your cursor to zero anytime you filter the set so you can always keep the behavior consistent.

提交回复
热议问题