2017-04-19 31 views
10

我想在React中的div上使用keyDown事件。我這樣做:onKeyDown事件不適用於React中的div

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

    componentWillUnmount() { 
     document.removeEventListener("keydown", this.onKeyPressed.bind(this)); 
    }  

    onKeyPressed(e) { 
    console.log(e.keyCode); 
    } 

    render() { 
    let player = this.props.boards.dungeons[this.props.boards.currentBoard].player; 
    return (
     <div 
     className="player" 
     style={{ position: "absolute" }} 
     onKeyDown={this.onKeyPressed} // not working 
     > 
     <div className="light-circle"> 
      <div className="image-wrapper"> 
      <img src={IMG_URL+player.img} /> 
      </div> 
     </div> 
     </div> 
    ) 
    } 

它工作正常,但我想在React樣式中做更多。我試過

 onKeyDown={this.onKeyPressed} 

上的組件。但它沒有反應。我記得它適用於輸入元素。

Codepen:http://codepen.io/lafisrap/pen/OmyBYG

我該怎麼辦呢?

回答

19

您應該使用的tabIndex屬性要能聽onKeyDown事件上反應的股利。設置tabIndex =「0」應該激發你的處理程序。

1

你需要它這樣

<div 
    className="player" 
    style={{ position: "absolute" }} 
    onKeyDown={this.onKeyPressed} 
    tabIndex="0" 
    > 

如果onKeyPressed未綁定到this寫,然後嘗試使用箭頭功能重寫或組件constructor綁定。

+0

對不起。我確信,我只是忽略了這一點。但這不是問題。它仍然不起作用。 – Michael

+0

已更新的答案。您應該在按任意鍵之前點擊div或將其聚焦。 – Panther

+0

我做到了。它不工作。我更新了上面的代碼。它適用於DOM命令,但不適用於React樣式。 – Michael

0

你在純Javascript中考慮太多。在這些React生命週期方法中擺脫聽衆,並使用event.key而不是event.keyCode(因爲這不是JS事件對象,它是React SyntheticEvent)。你的整個組件可以像這樣簡單(假設你沒有在構造函數中綁定你的方法)。

onKeyPressed(e) { 
    console.log(e.key); 
} 

render() { 
    let player = this.props.boards.dungeons[this.props.boards.currentBoard].player; 
    return (
    <div 
     className="player" 
     style={{ position: "absolute" }} 
     onKeyDown={(e) => this.onKeyPressed(e)} 
    > 
     <div className="light-circle"> 
     <div className="image-wrapper"> 
      <img src={IMG_URL+player.img} /> 
     </div> 
     </div> 
    </div> 
) 
} 
+0

這正是我想要寫的。但是,地獄,它不會。這是codepen:http://codepen.io/lafisrap/pen/OmyBYG。如果您註釋275行,則鍵盤輸入(光標鍵)不起作用。 onKeyDown在第307行。 – Michael

+0

keyCode我用於光標鍵,因爲它們不返回任何字符。 – Michael

+0

React不使用Javascript事件對象,所以沒有keyCode屬性。這個'event'對象是一個React [SyntheticEvent](https://facebook.github.io/react/docs/events.html)。 – steel