onKeyDown event not working on divs in React

前端 未结 7 1154
北恋
北恋 2020-12-02 11:11

I want to use a keyDown event on a div in React. I do:

  componentWillMount() {
      document.addEventListener(\"keydown\", this.onKeyPressed.bind(this));
          


        
7条回答
  •  孤城傲影
    2020-12-02 11:32

    Using the div trick with tab_index="0" or tabIndex="-1" works, but any time the user is focusing a view that's not an element, you get an ugly focus-outline on the entire website. This can be fixed by setting the CSS for the div to use outline: none in the focus.

    Here's the implementation with styled components:

    import styled from "styled-components"
    
    const KeyReceiver = styled.div`
      &:focus {
        outline: none;
      }
    `
    

    and in the App class:

      render() {
        return (      
          
              Display stuff...
          
        )
    

提交回复
热议问题