イベントハンドラのライフサイクルを制御するのに、focus
およびblur
イベントを使用できます。
render() {
return (
<input ref={inputLoaded} type="text" />
);
},
inputLoaded(input) {
input.addEventListener('focus', this.addEventListeners);
input.addEventListener('blur', this.removeEventListeners);
this.input = input;
},
componentWillUnmount() {
this.input.removeEventListener('focus', this.addEventListeners);
this.input.removeEventListener('blur', this.removeEventListeners);
window.removeEventListener('keydown', this.handleKey);
},
addEventListeners() {
window.addEventListener('keydown', this.handleKey);
},
removeEventListeners() {
window.removeEventListeners('keydown', this.handleKey);
},
handleKey(event) {
// this only gets called if input is focused.
// do something with this key
}
また、あなたはその後、state
変数を制御入力は、いくつかの作業を行う前に、handleKey
メソッド内でフォーカスがあるかどうかを確認するためにfocus
とblur
イベントを使用することができます。
イベントリスナーを 'document'または' window'に付ける際に特に問題はありますか? –
私はいつも発砲しないように私のイベントを好む。それが入力にちょうど添付されている場合、それは私がそれを集中させたときにのみ発火します。これはすべてのページに表示される検索バーで、イベントがすべてのページで多く発生することを意味します。 – kjonsson
イベントは、イベントリスナーを追加する場所に関係なく、DOM全体を起動します。それらを止める唯一の方法は 'stopPropagation'と' preventDefault'です。 –